Carregar o combobox

Question: Quando salvo um dado no combo box, e nesse combo box tem duas opções (gasolina, diesel, alcool, gas natural)
Quando seleciono diesel e salvo funciona normalmente.
O problema é quando quero carregar o combo box salvo sempre aparece o primeiro valor do combo, ou seja, a gasolina.
Como é que faço para quando o usuário carregar as informações ele possa ver no combo box o valor selecionado por ele?
O código está abaixo
public frmCadVeiculo2()
{
    InitializeComponent();

    List<Combustivel> itens = new List<Combustivel>();
    itens.Add(new Combustivel() { IDCombustivel = "Ga", Nome = "Gasolina" });
    itens.Add(new Combustivel() { IDCombustivel = "Di", Nome = "Diesel" });
    itens.Add(new Combustivel() { IDCombustivel = "Al", Nome = "Álcool" });
    itens.Add(new Combustivel() { IDCombustivel = "GN", Nome = "Gás Natural" });

    cbTipoCombustivel.DataSource = itens;
    cbTipoCombustivel.ValueMember = "IDCombustivel";
    cbTipoCombustivel.DisplayMember = "Nome";
}

Answer: Implemente o método abaixo no seu formulário e quando você carregar os dados salvo, passe para o método o combustivel selecionado:
private void SelecionarTipoCombustivel(Combustivel combustivel)
{
    cbTipoCombustivel.SelectedValue = combustivel.IDCombustivel;
}

Exemplo de uso:
public frmCadVeiculo2()
{
    InitializeComponent();

    List<Combustivel> itens = new List<Combustivel>();
    itens.Add(new Combustivel() { IDCombustivel = "Ga", Nome = "Gasolina" });
    itens.Add(new Combustivel() { IDCombustivel = "Di", Nome = "Diesel" });
    itens.Add(new Combustivel() { IDCombustivel = "Al", Nome = "Álcool" });
    itens.Add(new Combustivel() { IDCombustivel = "GN", Nome = "Gás Natural" });

    cbTipoCombustivel.DataSource = itens;
    cbTipoCombustivel.ValueMember = "IDCombustivel";
    cbTipoCombustivel.DisplayMember = "Nome";

   //Aqui você faz a leitura da sua fonte de dados onde você salvou a seleção do usuário.
   Combustivel combustivelSelecionado=LerDaFonteDeDados();

   //Aqui faz a seleção do combobox;
   SelecionarTipoCombustivel(combustivelSelecionado);
}

Comment: Oi Tiago, blza?
Primeiramente muito obrigado mesmo pela ajuda, sanou 70%,
mas estou com mais uma duvida, esse LerDaFonteDeDados() seria a lista de itens?
Comment: Esse método LerDaFonteDeDados()
Se a fonte de dados é a lista
Como implementaria esse método?
Comment: Consegui, Resolveu o problema, Muitissimo obrigado
Comment: A lista é uma fonte de dados de opções do jeito que você fez está certo,porém agora, você precisa de uma fonte de dados do usuário. Por exemplo: você precisa persistir o dados do usuário, assim quando ele reabrir o seu app ele irá ler desta fonte de dados (pode ser arquivo, base de dados e etc...) e irá mostrar para o usuário a seleção dele.
Comment: Consegui, Resolveu o problema, Muitissimo obrigado

Carregar o combobox


Stylus compiling doing wrong

Question: everybody, hope you will help me out. I've start styling in styles and everything was with few block of website. But when I start to write div's for gallery (here's code of it)
body
    clearfix()
    text-align center
    background url('./bgh1.jpg') no-repeat center center fixed
    background-size(cover)

#gallery
    margin-left 6%
    width 88%
    display block
    margin-left auto
    margin-right auto
    height 500px
    background black

    #line1
        width 980px
        height 345px
        background #ffffff

        #col1
            width 500px
            height 500px
            border 2px solid black
            img
                max-width 100%
                max-height 100%

It compiled with lot of mistakes
#gallery {
  margin-left: 6%;
  width: 88%;
}
#gallery display block {
  margin-left: auto;
}
#gallery margin-right auto {
  height: 500px;
  background: #000;
}
#gallery margin-right auto #line1 width 980px {
  height: 345px;
  background: #fff;
}
#gallery margin-right auto #line1 #col1 {
  width: 500px;
  height: 500px;
  border: 2px solid #000;
}
#gallery margin-right auto #line1 #col1 img {
  max-width: 100%;
  max-height: 100%;
}

This command I've been using for compiling
stylus -w views/stylesheets/styl.styl -o views/style.css

Answer: See Selectors: Indentation:

Whitespace is significant [...]

You are mixing whitespaces and tabs (even on the same lines). Even if this looks OK in your editor, this might cause problems when whitespace is significant. So you should configure your editor to replace tabs with single whitespaces to avoid that problem.

Stylus compiling doing wrong


Thymeleaf Spring JSF

Question: Estou tentando fazer a internacionalização de templat, usando

Thymeleaf 3.0
Spring 4.2.3
JSF 2.2

Que é enviado junto a um e-mail.
#{i18N.descriptionPortal}

Quando imprime no html do e-mail fica assim
??i18N.descriptionPortal_pt_BR??

o Thymeleaf não sabe do i18N que funciona nas paginas JSF, alguma dica de como parametrizo isso?
Configuração referente ao i18N e thymeleaf
@Configuration(value = "webapp")
@EnableWebMvc
@EnableTransactionManagement
@EnableScheduling
@ApplicationScoped
public class AppInitializer extends WebMvcConfigurerAdapter implements WebApplicationInitializer, ApplicationContextAware
{

    private ApplicationContext          applicationContext;

    @Override
    public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer)
    {
        configurer.enable();
    }

    @Override
    public void onStartup(final ServletContext servletContext) throws ServletException
    {
        final AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(Config.class);
        //definido o listener do spring para o contexto
        servletContext.addListener(new RequestContextListener());
        servletContext.addListener(new ContextLoaderListener(ctx));
        ctx.setServletContext(servletContext);
    }

    @Bean
    @Autowired
    public ViewResolver viewResolver(@Qualifier("templateEngine") final TemplateEngine templateEngine)
    {
        final ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine);
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    @Bean(name = "templateEngine")
    public TemplateEngine templateEngine() throws Exception
    {
        final SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        engine.afterPropertiesSet();
        return engine;
    }

    private ITemplateResolver templateResolver()
    {
        final SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/classes/mail/");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }

    @Bean(name = "msg")
    public MessageSource messageSource()
    {
        final ResourceBundleMessageSource message = new ResourceBundleMessageSource();
        message.setBasenames("messages/messages", "messages/build");
        message.setDefaultEncoding("UTF-8");
        message.setUseCodeAsDefaultMessage(true);
        return message;
    }

    @Bean
    public LocaleResolver localeResolver()
    {
        final SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        localeResolver.setDefaultLocale(new Locale("pt", "BR"));
        return localeResolver;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        final LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("msg");
        return lci;
    }
}

Essas são as formas que tentei usar no template, já fiz varias configurações e nada.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        .
        .
        .

Esse é o resultado no e-mail recebido

??msg.descriptionPortal_pt_BR?? ??descriptionPortal_pt_BR??

Esse é o erro quando tento usar no .xhtml a chave i18N
GRAVE: Error Rendering View[/mod/home.xhtml]
javax.el.ELException: /mod/home.xhtml: Property 'descriptionPortal' not found on type org.springframework.context.support.ResourceBundleMessageSource
    at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88)
    at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:82)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
    at org.primefaces.component.outputpanel.OutputPanelRenderer.encodeMarkup(OutputPanelRenderer.java:65)
    at org.primefaces.component.outputpanel.OutputPanelRenderer.encodeEnd(OutputPanelRenderer.java:41)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:89)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:72)
    at org.primefaces.component.outputpanel.OutputPanelRenderer.encodeMarkup(OutputPanelRenderer.java:65)
    at org.primefaces.component.outputpanel.OutputPanelRenderer.encodeEnd(OutputPanelRenderer.java:41)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1903)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:889)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1896)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1899)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1899)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:451)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.orm.hibernate5.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:151)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at com.sys.filters.SysFilterLogin.executeRequest(SysFilterLogin.java:194)
    at com.sys.filters.SysFilterLogin.processSession(SysFilterLogin.java:142)
    at com.sys.filters.SysFilterLogin.doFilter(SysFilterLogin.java:46)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at com.sys.filters.SysFilterAllRequest.doFilter(SysFilterAllRequest.java:55)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at com.sys.filters.SysCharacterEncodingFilter.doFilter(SysCharacterEncodingFilter.java:39)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2500)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2489)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Já fiz muitas outras configurações mas praticamente chego sempre nesse mesmo resultado
Answer: Este retorno do Themeleaf é que ele não encontrou o texto em pt_BR para a variável "descriptionPortal".
De uma olhada nesta resposta Utilizando i18n
Você basicamente precisa criar um arquivo messages_pt_BR.properties dentro de resources/i18n/
e ter a variável lá
descriptionPortal = Descrição do Portal em português

Adicione o parâmetro na tag que estiver utilizando, por exemplo:

Comment: Olhei o que sugeriu, tentei ajustar conformes dicas e nada, atualizei com partes do fonte e erro que estou tendo, a pergunta.
Comment: Dentro da pasta messages/messages, existe o arquivo messages_pt_BR? Fez o teste com o messages_en_US.properties? Tem que ver qual locale o thymeleaf esta reconhecendo.
Comment: Outra cosia, como definiu com default o pt_BR, tente utilizar o arquivo message.properties. Seu navegador/ SO tem locales como pt_BR?
Comment: Sim existe os arquivos,  messages_pt_BR.properties e  messages_en_US.properties.
Comment: Como você definiu com default = pt_BR, precisa existir o message.properties
Answer: Todo o problema era gerado da seguinte forma:

O Themeleaf injeta em seu source em algum lugar, ele só lê a interface MessageSource;
Que deve ter o bean messageSource
Como o JSF precisa java.util.ResourceBundle
Cria se um objeto singleton ResourceBundle
Nesse caso chamado de i18N

    @Component("i18N")
    @Scope("singleton")
    public class SysResourceBundleRead extends ResourceBundle implements Serializable, MessageSource{
     ..
     ..
     ..
    }

Veja o objeto esta implementando MessageSource
Agora na configuração recebo o objeto
@Qualifier("i18N")

@Bean(name = { "messageSource"})
@Autowired
public MessageSource messageSource(@Qualifier("i18N") final SysResourceBundleRead resourceBundleRead)
{
    return resourceBundleRead;
}

Então quem for usar com esse nome usa o mesmo objeto pensando que é messageSource, default

A configuração no jsf integrando o Spring fica assim
<application>
    <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    <el-resolver>com.sys.resolver.SysLocaleController</el-resolver>
    <resource-bundle>
        <base-name>messages.build</base-name>
        <var>build</var>
    </resource-bundle>
    <resource-bundle>
        <display-name>I18N</display-name>
        <base-name>messages.messages</base-name>
        <var>i18N</var>
    </resource-bundle>
    <locale-config>
        <default-locale>pt_BR</default-locale>
        <supported-locale>en_US</supported-locale>
        <supported-locale>pt_BR</supported-locale>
    </locale-config>
    <message-bundle>messages.messages</message-bundle>

</application>

Para usar no JSF usa assim:
#{i18N.descriptionPortal}

Para usar no themeleaf usa assim:
#{descriptionPortal}

Para usar no Spring usa assim:
@Qualifier(name = { "messageSource"})
@Autowired
public MessageSource messageSource;

Ou
@Qualifier(name = { "i18N"})
@Autowired
public SysResourceBundleRead i18N;

Ambas são o mesmo objeto, mas usam methodos diferentes para ler as chaves, então precisa ajustar sua classe para que haja essa sincronia.

Thymeleaf Spring JSF


How to prove this limit $\lim_{n\to\infty}\frac{p_1a_n+p_2a_{n-1}+\cdots+p_na_1}{p_1+p_2+\cdots+p_n}=a$

Question: If $p_k>0\quad(k=1,2,\cdots)$ and $$\lim_{n\to \infty}\frac{p_n}{p_1+p_2+\cdots+p_n}=0,\lim_{n\to\infty}a_n=a$$how to prove the limit$$\lim_{n\to\infty}\frac{p_1a_n+p_2a_{n-1}+\cdots+p_na_1}{p_1+p_2+\cdots+p_n}=a$$
Comment: Have you tried to use summation by parts?
Comment: It suffices to consider the case that $a=0$. For the general case observe $\frac{p_1a_n+p_2a_{n-1}+\cdots+p_na_1}{p_1+p_2+\cdots+p_n}= a + \frac{p_1(a_n-a)+p_2(a_{n-1}-a)+\cdots+p_n(a_1-a)}{p_1+p_2+\cdots+p_n}$.
Answer: Proof.  $\blacktriangleleft$ First a preparation.

Toeplitz Theorem. Suppose $n,k \in \mathbb N^*$ and $t_{n,k} \geqslant 0$ for all $n$ and $k \leqslant n$ satisfying that $\sum_{k=1}^n t_{n,k} = 1$ and $\lim_{n} t_{n,k}=0$ for all $k \leqslant n$. If $\lim a_n = a$, then we have
  $$
x _n = \sum_{k =1}^n t_{n,k} a_k\to a \quad [n \to \infty].
$$

To prove the theorem, it suffices to prove for $a = 0$, otherwise use $a_n - a$ to replace $a$, and the result remain unaltered since $\sum_{k =1}^n t_{n,k} =1$.
Since $a_k \to 0 [k \to \infty]$, there is some $M > 0$ s.t. $|a_k| \leqslant M$. For every $N \leqslant n-2$, we have
\begin{align*}
\varlimsup_n \left| \sum_{k=1}^n t_{n,k}a_k\right| &\leqslant
\varlimsup_n \left|\left(\sum_{k=1}^N + \sum_{k=N+1}^n t_{n,k}\right)a_k\right| \\
&\leqslant M \varlimsup_n \sum_{k=1}^n t_{n,k} + \varlimsup_n \sup_{k \geqslant N} |a_k| \sum_{k = N+1}^n t_{n,k}\\
&\leqslant MN \cdot 0 + \sup_{k\geqslant N}|a_k| \varlimsup_n \sum_{k=1}^n t_{n,k} \quad [\text{because }t_{n,k}\geqslant 0]\\
&= \sup_{k \geqslant N} |a_k| \to 0 \quad [N \to \infty],
\end{align*}
hence the theorem.
Now back to the question. Let
$$
t_{n,k} = \frac {p_{n-k+1}}{p_1 + p_2 + \cdots + p_n}.
$$
SInce $p_k > 0$ for all $k$, we have
$$
0 \leqslant t_{n,k}\leqslant \frac {p_{n-k+1}}{p_1 + p_2 + \cdots + p_{n-k+1}} \to 0 \quad [n \to \infty],
$$
hence $\lim_n t_{n,k} = 0$ for all $k \leqslant n$ by squeezing theorem. Now the conclusion follows the Toeplitz theorem, since clearly $\sum_{k = 1}^n t_{n,k} = 1$. $\blacktriangleright$
Note: the theorem above could be proved by the classic $\varepsilon$-$N$ definition, of course.
Answer: Let $\epsilon >0$. Then, there exists some $N$ such that, for all $n >N$ we have
$$|a_n-a| <\epsilon$$
Now, by the second condition, since $N$ is fixed you have
$$\lim_n \frac{(a_1-a)p_n}{p_1+...+p_n}+....+ \frac{(a_{N-1}-a)p_{n-N}}{p_1+...+p_n}=0$$
Therefore, there exists some $M$ such that, for all $n>M$ we have
$$\left|\frac{(a_1-a)p_n}{p_1+...+p_n}+....+ \frac{(a_{N-1}-a)p_{n-N}}{p_1+...+p_n}\right|< \epsilon$$
Then, for all $n>\max \{ N, M\}$ we have
$$\left| \frac{p_1a_n+p_2a_{n-1}+\cdots+p_na_1}{p_1+p_2+\cdots+p_n}-a \right| \leq
\\
\frac{p_1}{p_1+...+p_n}|a_n-a|+\frac{p_2}{p_1+...+p_n}|a_{n-1}-a|+..+\frac{p_{n-N+1}}{p_1+...+p_n}|a_N-a|+\\
+\left|\frac{(a_1-a)p_n}{p_1+...+p_n}+....+ \frac{(a_{N-1}-a)p_{n-N}}{p_1+...+p_n}\right|\\
\leq \frac{p_1+....+p_{n-N+1}}{p_1+...+p_n} \epsilon+\epsilon < 2 \epsilon
$$


Can Asterisk passwords be obtained by a malicious server?

Question: To make a long story short, a client phone was compromised and used to make illicit calls. An investigation revealed a port forwarding entry to the phone's web UI, which is "protected" by a 6 digit numeric password. We're assuming this was compromised, and are now trying to figure out how they got an extension password from there (it's not available to the UI, nor is it contained in the config file backups you can retrieve from the web UI.) One thing they can do via the web UI is change the registration server.
I know the password is never sent in clear text, but I think the main purpose of the challenge/response authentication is to ensure that the client is who they say they are, for the server's protection. I don't know how much protection is afforded to the client. So, my question: if an endpoint attempts registration against a malicious SIP server, can that server obtain the SIP credentials?
Answer: Attacks against phone sets are a current trend in VoIP hacking.  There are well known bugs in web GUI's of phones, that expose their contents (including SIP credentials used to register with the SIP server).  As some phone sets are directly attached to the internet it's difficult to protect them.  (If on an internal network then the GUI's should not be exposed)
One attack involves DNS poisoning which causes the endpoint to register with a foreign SIP server, and exposes the credentials.
While keeping phone firmware up to date is a good idea, be sure to use a PBX security system which can detect suspicious dialing patterns, unusual number/rate of calls in progress, etc.  Simple tools like 'fail2ban' will never catch such an attack.  As well, attacks using 'spread IP' make it hard to block unless your VoIP security system can detect them.
Have a look at this voip-info page on security voip-info and some suggestions on ideas and products to detect and block such attacks.
Comment: See above: "One attack involves DNS poisoning which causes the endpoint to register with a foreign SIP server, and exposes the credentials.".  So yes it exposes the credentials....
Comment: This does not answer the question: if an endpoint registers against a malicious server, can that server obtain the endpoint's credentials?


Performing a list operation in Python

Question: I am removing J1 from J. Corresponding to the removed indices, I want to alter Ci[1] and append to Ci as shown below but I am getting an error. I also present the expected output.
J=[2, 6, 9, 10]
J1=[6,10]
l=[]
l.append(J)
l.append([x for x in J if x not in J1])

Ci = [[0, 0, 0, 0], [10, 30, 50, 80]]
A=Ci[1]([x for x in J if x not in J1])
print(A)

The error is
in <module>
    A=Ci[1]([x for x in J if x not in J1])

TypeError: 'list' object is not callable

The expected output is
[[[0, 0, 0, 0], [10, 30, 50, 80]],[[10, 50]]]

Comment: Are you sure you want `[[[0, 0, 0, 0], [10, 30, 50, 80]],[[10, 50]]]` and not just `[[0, 0, 0, 0], [10, 30, 50, 80], [10, 50]]`?
Comment: What is `A=Ci[1]([x for x in J if x not in J1])` supposed to mean? It's not correct python and I can't tell what you expected from that line
Comment: I want to use the same indices for ```J``` to remove specific elements from ```Ci[1]```.
Answer: You can use zip to iterate on two lists simultaneously:
A = [Ci, [[x for x,y in zip(Ci[1],J) if y not in J1]]]
print(A)
# [[[0, 0, 0, 0], [10, 30, 50, 80]], [[10, 50]]]

Comment: Your output is very close to mine but this is what I am looking for: ```[[[0, 0, 0, 0], [10, 30, 50, 80]],[[10, 50]]]```.
Comment: @isaacmodi123 And now?
Comment: ```[[[0, 0, 0, 0], [10, 30, 50, 80]], [10, 50]]``` is your output. There are missing brackets in ```[10,50]```.
Comment: @isaacmodi123 Fair point. I edited.
Answer: You can collect the indices first,
lidx = [i for i in range(len(J)) if J[i] not in J1]
A = [Ci, [Ci[1][i] for i in lidx]]

Comment: (Of course this is all just guessing on my part - without more context on this question I have no idea what `Ci` and `A` are used for anyway)
Comment: ```[[[0, 0, 0, 0], [10, 30, 50, 80]], [10, 50]]``` is your output. There are missing brackets in ```[10,50]```. It should be ```[[10, 50]]```.
Comment: Then `A = [Ci, [[Ci[1][i] for i in lidx]]]`, but in second element `[[Ci[1][i] for i in lidx]]` the outer brackets seems not neccesary. Why you need it?
Comment: @rustyhu So the dimensions are consistent. If you do just `[Ci, [Ci[1][i] for i in lidx]]`, then the elements in the first part have a depth of 3, but the elements in the second part of a depth of only 2. And if python was stronly typed you wouldn't be able to write a consistent type for `A`, is it a List(List(List(int))) or a List(List(int))?
Comment: @rustyhu When you write `Ci[1][i]` you're dereferencing `Ci` twice: once with `[1]`, once with `[i]`. So, to keep types consistent, it makes sense to rereference it twice, with `[[ ... ]]` and not just `[ ... ]`.

Performing a list operation in Python


Restrict access to a section of the site implemented by a custom module

Question: I have a site with two different type of users: clients and anonymous users.
I'm currently building custom modules to handle a "client administration" section of the site, where clients are able to change their profiles, modify custom settings, etc. There is a section of the site "client" users are able to access, but regular users are not.
How can I restrict access to that section to only a particular class of user?
Answer: If you implement hook_permission in your custom module, you can control the access of your client administration section.

Set up roles. You've done this already with the client role.
Implement hook_permission():
function MODULE_permission()
{
    return array(
        'access client administration' => array(
            'title'       => t('Access Client Administration'),
            'description' => t('Allow users to access client administration'),
        ),
    );
}

When you define hook_menu(), make sure you set the permissions accordingly:
function MODULE_menu()
{
    $items['client_administration'] = array(
        'title' => 'Client Administration Page',
...
        'access arguments' => array('access client administration'),
    );

    return $items;
}

Go to admin/people/permissions and set the permissions for 'Access Client Administration' to your client role.
Answer: Use hook_permission() in your custom module to define a new permission (e.g. "use module foo") and then assign that permission to the appropriate roles. Then check permissions with user_access() wherever necessary in your module.


How to evaluate $\int_0^1 \int_0^1 \int_0^{\frac{\pi}{4}} \frac{a^2 + b^2 \sin^2 x}{b^2 + a^2 \cos^2 x} \tan x \, dx \, db \, da $

Question:
$$
\Omega = \int_0^1 \int_0^1 \int_0^{\frac{\pi}{4}} \frac{a^2 + b^2 \sin^2 x}{b^2 + a^2 \cos^2 x} \tan x \, dx \, db \, da
$$

$$
\Omega_1 = \int_0^{\frac\pi4} \frac{a^2 + b^2 \sin^2 x}{b^2 + a^2 \cos^2 x} \tan x \, dx \quad \text{(let } t = \tan x \text{)}
$$
$$
= \int_0^1 \frac{a^2 + (a^2 + b^2) t^2}{b^2 + a^2 + b^2 t^2} \cdot \frac{t}{1 + t^2} \, dt
$$
$$
= \frac{1}{2} \int_0^1 \frac{a^2 + (a^2 + b^2) t}{(a^2 + b^2 + b^2 t)(1 + t)} \, dt
$$
$$
= \frac{a^4 + b^4 + a^2 b^2}{2a^2 b^2} \int_0^1 \frac{b^2}{a^2 + b^2 + b^2 t} \, dt - \frac{b^2}{2a^2} \int_0^1 \frac{1}{1 + t} \, dt
$$
$$
= \frac{1}{2} \left( \left(\frac{b}{a}\right)^2 + \left(\frac{a}{b}\right)^2 + 1 \right) \log \left(1 + \frac{\left(\frac{b}{a}\right)^2}{1 + \left(\frac{b}{a}\right)^2} \right) - \frac{\log(2)}{2} \left(\frac{b}{a}\right)^2
$$
Answer: Too long for comment
While the direction you've taken will probably work out just fine, we may also consider integrating w.r.t. $a$ or $b$ first. We have for instance
$$\begin{align*}
\frac{a^2 + b^2\sin^2x}{a^2\cos^2x + b^2} \tan x &= \sec^2x \tan x + b^2 \frac{\left(\sin^2x-\sec^2x\right)\tan x}{a^2\cos^2x+b^2} \\
\implies \int_0^1 \cdots da &= \sec^2x \tan x + b^2 \int_0^1 \frac{\tan^3x-\sec^4x\tan x}{a^2+b^2\sec^2x} \, da \\
&= \sec^2x \tan x + b \left(\tan^2x-\sec^4x\right)\sin x \arctan\left(\frac{\cos x}b\right)
\end{align*}$$
The integral w.r.t. $b$ can be done by parts, and the subsequent $x$-integral can be expanded into several trivial integrals plus a linear combination of integrals of the form $(n\in\{0,1,2,3\})$
$$\int_0^{\tfrac\pi4} \arctan(\cos x) \cos(2nx) \sec^3x \tan x \, dx$$
It's likely tedious work, but these should be doable by applying Leibniz's integral rule to
$$I(\alpha) = \int_0^{\tfrac\pi4} \arctan(\alpha\cos x) \cos(2nx) \sec^3x \tan x \, dx$$


Como fazer um link com cada item de uma lista de retorno da API?

Question: Estou fazendo um projeto com react e fiz uma página de campo de busca que me trás uma listagem de nomes, até essa parte ok. Porém preciso que cada nome desse da lista seja um link que me leve para uma informação específica desse "cliente". Fiz alguma tentativas e apenas consegue fazer um link que me leva para todas as respostas de uma vez, não a resposta específica. Alguém saberia me informar o que estou fazendo de errado?
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

 export default function Responsible() {
   const [responsaveis, setResponsaveis] = useState([]);

   useEffect(() => {
   let nomeResp = localStorage.getItem('nomeResp');
   nomeResp = JSON.parse(nomeResp);
   setResponsaveis(nomeResp);
   }, []);

   return (
    <>

Responsáveis

       {responsaveis.map((resp) => (

       <Link to="/DetalhesResponsavel">{resp}</Link>

      ))}

  </>
 );
}

A página "/DetalhesResponsavel" que era para vir apenas a informação do link do "cliente" que cliquei está assim:
   import React, { useEffect, useState } from 'react';

   export default function RespDetails() {
     const [responsaveis, setResponsaveis] = useState([]);
     useEffect(() => {
     let detResp = localStorage.getItem('detResp');
     detResp = JSON.parse(detResp);
     setResponsaveis(detResp);
   }, []);

  return (
   <>

Responsável ID :

      {responsaveis.map((det) => (

{det}

       ))}

   </>
 );
}

O que acontece é que está vindo todas as informações de uma vez, como se toda a lista de nomes fossem um link só e levassem a todas as informações de uma vez.
Answer: Olá, o que voce fazer eram dois componentes (ou páginas no caso)
O primeiro gera uma lista com vários links
O segundo deveria ser uma página com informações de cada item da lista, correto?
Se for isso, pensa assim "Como o segundo componente saberia qual informação deveria exibir? De qual item da lista?"
No segundo componente que voce criou em nenhum momento você diz qual item da lista ele deveria exibir, ou seja, ele não consegue identificar. Além disso se você ler a lógica escrita você diz para ele exibir todos os items da lista:
{responsaveis.map((det) => (

{det}

 ))}

Uma possivel solução:
Existem diversas saídas para você identificar qual item da lista você quer exibir, uma das saídas poderia ser a seguinte:
No primeiro componente passar o id pelo link:

   <Link to=`/DetalhesResponsavel/${resp.id}`>{resp}</Link>

No segundo componente identificar pelo link:
import React, { useEffect, useState } from 'react';

export default function RespDetails() {
   const [responsaveis, setResponsaveis] = useState([]);
   const pathname = window.location.pathname;
   const id = pathname.split('/')[-1];
   useEffect(() => {
     let detResp = localStorage.getItem('detResp');
     detResp = JSON.parse(detResp);
     setResponsaveis(detResp);
   }, []);

  return (
   <>

Responsável ID :

      {responsaveis.map((det) => (
        if (det.id === id) {

{det}

        }
       ))}

   </>
 );
}

Nas rotas talvez você tenha que modificar (nao sei como está):
Talvez dê algum erro por ter modificado o link, daí já não sei o que você está usando para relacionar o link com os componentes, mas caso você esteja usando  não utilize "exact path", use apenas o "path"
Tem um exemplo bem parecido que você quer fazer aqui no tutorial do react router:
https://reactrouter.com/docs/en/v6/getting-started/tutorial
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Image Clustering with K-means - Postprocessing

Question: I did some clustering on an image (each pixel is an observation that has 5 variables associated with it), I get pretty detailed results but they are a little bit noisey... I think. I used K-means. Does anyone have a nice idea on how to reduce the noise a bit? anyone know some postprocessing for K-means. I would usually just apply a median filter to the image or something of the sort but I want to know if there is something a little nicer out there.
p.s. this was all done in python by the way, only brightly colored pixels were clustered.
Answer: When you did K-means, presumably you treated the attributes at each pixel as a $5$-tuple of real values and you clustered them based on Euclidean distance in $\mathbb{R}^5$.  To achieve spatial contiguity in the clustering, include spatial coordinates among the attributes.  If you include (say) the two Cartesian map coordinates, you will effectively be doing the K-means clustering in $\mathbb{R}^7 \approx \mathbb{R}^5 \times \mathbb{R}^2$.  I have written this as a Cartesian product to emphasize that there is a tuning parameter available to you: the relative sizes of the last two (spatial) attributes compared to the first five attributes.  By rescaling the spatial attributes you can vary the amount by which they influence the clustering.  With only a little influence, the result will be noisy; with a lot of influence, you will be performing purely spatial clustering.  Experiment to identify an optimal value.
(This is an approach I have used many times.  It is not always as successful as I would like, but it works sufficiently often to be worth looking at in any case.)
Comment: I like this idea a lot. Sorry I had not read this I dont know why. Would finding this optimal weight for the coordinates variables be done only visually? Because I have a huge amount of images and I the main idea is to automatize the process as much as possible. I have also read about using region growing for the same purpose. Do you have any experience with this? @whuber
Comment: One would hope that tuning the procedure on one or a small number of images would enable it to work satisfactorily on all similar images.  The tuning doesn't have to be visual, but to automate it, you would need some way to quantify how well you think it's working.
Comment: Do you have any idea on as to what kind of statistic to use to quantify this? I, intuitevely would like the clusters to be geographically homogeneous together i.e. maybe a lower bound on the number of adjacent pixels in the neighbourhood belonging to the same cluster could help? But that's just from the top of my head...
Comment: Unfortunately, if you require the clusters to be as geographically homogeneous as possible, then the answer is to downweight the attributes to zero. You need to quantify the amount by which you are willing to trade off an decrease in geographic homogeneity for an increase in the homogeneity of the attributes within the clusters.
Answer: A very simple-minded way to reduce the noise would be to apply a filter that creates a new image in which each pixel's ID is replaced by the most common ID found among its neighbours. (Don't do this calculation in-place, put the answers in a new matrix.)
However, it'd be much better to use a Conditional Random Field model rather than K-means, since it directly includes the idea of pixels' neighbourliness.
(Also have a look at this comparison of clustering methods implemented in scikit-learn.)
Comment: Welcome to our site, Dan!  This recommendation is called a "majority filter"; as such, it is offered as a substitute for the median filter--but that's exactly the kind of approach the OP is trying to avoid. Your suggestion of a CRF is intriguing: would you care to expand on how it would be applied here?
Comment: I actually started off using gaussaian mixtures - EM algorithm to find clusters in the images but they are quite big ( 5000 x 5000 x 5 bands) and this method apparently doesn't work well at all for data of this size. I would also be very interested in you expanding a bit on how to apply crf's here.


Jquery Issue with fadeTo on hover

Question: So basically I am trying to have div.show fade in on hover and then when you stop hovering, have it fade back to an opacity of 0.
However, I cannot get the div to fade back to 0 when you stop hovering.
Here is my code:
$(document).ready(function(){
    $("div.post.photo").live('hover', function() {
        $(this).children("div.show").fadeTo("slow", .7);
    }, function(){
        $(this).children("div.show").fadeTo("slow", 0);
    });
});

Thank you
Answer: You need to explicitly check for the mouseenter and mouseleave events using the event.type. You shouldn't need to bind them twice.
$(document).ready(function(){
    $("div.post.photo").live('hover', function(event) {

        if( event.type === 'mouseenter')
            $(this).children("div.show").fadeTo("slow", .7);
        else if( event.type === 'mouseleave' )
            $(this).children("div.show").fadeTo("slow", 0);
    });
});

Here's a fiddle. Personally i would use .on but i'm not sure what version of jQuery you are using.
Answer: I am pretty sure you should be fading it back to 1, not 0.
Also live() only takes one handler. You need to append mouse out event separately.
fiddle
Comment: That does not worth either :/
Comment: That's the opposite of what he is trying to do. It's supposed to fade out, not back to 100% opacity
Comment: @NateB and as I noted in my answer I think that is the opposite of what he actually needs. Unless precondition is that `.show` starts as 0 opacity, but there is nothing about that in the OP. Regardless, it only takes changing 1 to 0 and adding `opacity:0` to the `.show` to flip this around.
Comment: Sorry about that, it is set to display none in css.
Comment: Well, this works.  Thanks a bunch, I had to change the numbers, which was fine.  Interesting that delegate works without the use of live on new elements, whereas on does not?
Comment: You shouldn't need to bind them separately, you can just check the `event.type` to see what kind of event was triggered, if it was `mouseenter` or `mouseleave`
Answer: I find that this works if you use .hover() instead of .live(), so I think the issue is that .live() doesn't support the hover event, perhaps because .live() only has one handler function, not two.
In jQuery 1.7+, this seems to work (breaking it up into two event handlers and modernizing to .on()):
$(document).ready(function(){
    $(document.body).on("mouseenter", "div.post.photo",
        function() {
            $(this).children("div.show").fadeTo("slow", .7);
        }
    );

    $(document.body).on("mouseleave", "div.post.photo",
        function() {
            $(this).children("div.show").fadeTo("slow", .0);
        }
    );
});

You can see it work here: http://jsfiddle.net/jfriend00/YV2nU/.
FYI, I switched to .on() because .live() is deprecated in jQuery 1.7+.
Comment: Hmm, my issue is that I use an infinite scroll script that fetches new posts when you scroll to the bottom of a page.  Thus the live allowed the script to continue working on new elements.  When I use your suggestion the script does not work on any new `div.post.photo`'s fetched.
Comment: I could help if I could see your actual page.  Aside from that, `.on()` is a direct replacement for `.live()` so it should offer the same dynamic behavior.  The one thing you could improve in my code example is to change `document.body` to a parent div that is always there, but closer to the items that are dynamically added.
Comment: However, I used an answer above that used `delegate` instead of `on` and it works like a champ.  Thanks for your help though.
Answer: Your problem is that hover is not a Javascript event, it is JQuery shorthand for the mouseenter and mouseleave events, so it can't be used in the live method like that. You need to bind them separately. Additionally, you should note that the .live() method is deprecated. The JQuery documentation gives instruction on what methods are better to use.

Jquery Issue with fadeTo on hover


Why does Fisher use covariance when only variance is needed?

Question: With reference to the following image from here: (can not inline it due to unsupported format)
https://wikimedia.org/api/rest_v1/media/math/render/svg/9af8aa035642689bb2004047416b069a15406447
If we are interested in maximizing the gap between the data subsets associated with the same labels divided by the sum of the variance of these data subsets, why are we using the covariance matrix as opposed to the variance?
Another example where I see this apart from the wikipedia page is here, specifically this image:
The numerator of the not-simplified score function makes sense (applying linear transformation to means and computing their distance, which we want to maximize). However, I don't understand a single part of the denominator (this includes not understanding why we use covariance instead of variance and why we multiply transpose of transformation with covariance and transformation.
Why do we use covariance instead of variance in the fisher score function, and why is the covariance surrounded by the transpose of the transformation and the transformation?
Answer: In this problem you have what is essentially paired-data, with an equal number of observations of features from two objects/classes, where values in the classes can be correlated with one another (i.e., they are not assumed to be statistically dependent).  Because correlation between features can occur, the overall variance of any linear combination of the feature values will depend on their correlation.  This means that we need to know the variances of the individual features, but also the covariance between them.  This is the reason we use a whole covariance matrix in this case.
In this case, each random vector $\mathbf{X}_i$ has some mean vector $\boldsymbol{\mu}_i$ and some covariance matrix $\mathbf{C}_i$.  The latter is a full specification of the variances of each feature in the random vector, and also the covariances between the features in the random vector (from which we get the correlations of the features).  A "linear discriminant" is effectively just a measure that aggregates the features by some linear function, so that we can compare an aggregate measure across multiple objects/classes.  If we use the linear discriminant $Z(\mathbf{X}_i) = \boldsymbol{\beta}^\text{T} \mathbf{X}_i = \sum_k \beta_k X_{i,k}$ then the mean and variance of this "discriminant" can be found using the ordinary rules of mean and variance of linear functions:
$$\begin{equation} \begin{aligned}
\mathbb{E}(Z(\mathbf{X}_i)) &= \mathbb{E}(\boldsymbol{\beta}^\text{T} \mathbf{X}_i) = \boldsymbol{\beta}^\text{T} \mathbb{E}(\mathbf{X}_i) = \boldsymbol{\beta}^\text{T} \boldsymbol{\mu}_i = \sum_k \beta_k \mu_k, \\[8pt]
\mathbb{V}(Z(\mathbf{X}_i)) &= \mathbb{V}(\boldsymbol{\beta}^\text{T} \mathbf{X}_i) = \boldsymbol{\beta}^\text{T} \mathbb{V}(\mathbf{X}_i) \boldsymbol{\beta} = \boldsymbol{\beta}^\text{T} \mathbf{C}_i \boldsymbol{\beta} = \sum_k \sum_l \beta_k \beta_l C_{i,k,l}.
\end{aligned} \end{equation}$$
From these formulae we see that the variance of the discriminant $Z$ depends on the covariance matrix $\mathbf{C}_i$ and is a quadratic form.  This is merely a result of the fact that when individual features are correlated, the overall variance of the "linear discriminant" is affected by these correlations.  If you would like to learn more about this, I would suggest learning a bit about probability results for random vectors, and in particular, look at moment rules for linear functions.  The variance of a linear combination of random variables is a quadratic form, as in the above formula.  Hopefully this explanation gives you a starting point for this inquiry.
Comment: Is the fact that V((B_T)(X_i)) equals (b_T)V(x_I)(b) because V(c(x_i)) equals (c^2)V(x_I), where V is the variance function and c is a constnat? In addition, can you provide an intuitive explanation for "Because correlation between features can occur, the overall variance of any linear combination of the feature values will depend on their correlation." Finally, can you clarify "In this case, each random vector Xi has some mean vector μi and some covariance matrix Ci"? (despite research, I can't figure out what random vector means here, can you rephrase the sentence)?
Comment: The way I'm interpreting your random vector sentence, you are saying each vector has an associated mean and covariance, when a set of vectors have a mean and covariance, not per vector.


How to calculate $\int_{x^2+y^2+z^2\leq R^2}\frac{dxdydz}{\sqrt{(x-a)^2+(y-b)^2+(z-c)^2}}$, where $a^2+b^2+c^2>R^2$?

Question: Let$a^2+b^2+c^2>R^2$, calculate $\int_{x^2+y^2+z^2\leq R^2}\frac{dxdydz}{\sqrt{(x-a)^2+(y-b)^2+(z-c)^2}}$.
Let $(x,y,z)=(a+r\sin\phi\cos \theta,b+r\sin\phi\sin \theta,z=c+r\cos\phi)$, but I don't know how to transform the integration region. Is there any good idea?
Comment: you're integrating a harmonic function over a ball, so the integral is the value of the function at the center of the ball, times the volume of the ball
Comment: It's amazing, is there a more elementary way to calculate it directly?
Answer: Consider a transformation to a coordinate system centered at the point $(a,b,c)$ but rotated such that the origin lies on the $z$ axis relative to the point $(a,b,c)$. This gives us the integral
$$I = \iiint\limits_{x^2+y^2+\left(z-\sqrt{a^2+b^2+c^2}\right)^2\leq R^2}\frac{dV}{\sqrt{x^2+y^2+z^2}}$$
Then convert to spherical coordinates and do the angular integral first.
$$I = \int_0^{2\pi}\int_{\sqrt{a^2+b^2+c^2}-R}^{\sqrt{a^2+b^2+c^2}+R}\int_0^{\cos^{-1}\left(\frac{r^2+a^2+b^2+c^2-R^2}{2r\sqrt{a^2+b^2+c^2}}\right)}r\sin\theta\:d\theta\:dr\:d\theta$$
$$= \frac{\pi}{\sqrt{a^2+b^2+c^2}}\int_{\sqrt{a^2+b^2+c^2}-R}^{\sqrt{a^2+b^2+c^2}+R}2r\sqrt{a^2+b^2+c^2}-(r^2+a^2+b^2+c^2-R^2)\:dr$$
$$= \frac{\pi}{\sqrt{a^2+b^2+c^2}}\left(2R(a^2+b^2+c^2+R^2)-2R(a^2+b^2+c^2)-\frac{2}{3}R^3\right)$$
$$\implies \boxed{I = \frac{4\pi R^3}{3\sqrt{a^2+b^2+c^2}}}$$
which is exactly the volume of the sphere times the value of the original integrand at the origin.
Comment: @Ychen The equation of the sphere tells us $$x^2+y^2+z^2=2z\sqrt{a^2+b^2+c^2}-(a^2+b^2+c^2-R^2)$$ $$\implies r^2 = 2r\cos\theta\sqrt{a^2+b^2+c^2}-(a^2+b^2+c^2-R^2)$$ when converting to polar coordinates. From here it is a simple matter of solving for cosine. The $r$ bounds are found by simply considering the minimum and maximum reach of the $r$ variable, which by the cleverly chosen symmetry occurs directly on the $z$ axis.
Comment: How do you determine the range of values for $r$ and $\theta$?


Map a closed function $f: (1,4) \rightarrow (1,4)$ without fixed point

Question: I need to find a continuous function $f (1,4) \rightarrow (1,4)$ that has no fixed points. I realise that the entire function then either lies above $y=x$ or below $y=x$ but I don't know how to get to an actual function so I need some help to get there.
Thanks in advance.
Comment: The square root function maps $(0,1)$ onto itself with no fixed points.  Try shifting/scaling this function to fit your needs.
Comment: Hint: Try linear functions. (i.e. functions of the form $f(x) = ax+b$. What are the requirements on $a$ and $b$?
Comment: great hint, if I use $y=\sqrt{4x}$ then I think it works. Thanks!
Answer: So you need that $g(x)=f(x)-x$ has no roots inside the interval. However you will find that $g$ needs to have roots at $1$ and $4$. Thus try something like $g(x)=c(x-1)(x-4)$.
Answer: $f(x)=1+(x-1)^2/3.$ By analogy to $g(x)=x^2/3<x$ for $x\in (0,3).$


how to change the value of the form in the preprocess functions or get the value of the function preprocess

Question: I need to get the value of preprocess function and write it in the form #default_value, while my form is a variable that preprocess functions
I create custom module
<?php
/**
 * Реализация template_preprocess_comment()
 **/
function comment_email_form_preprocess_comment(&$variables){
    $variables['content']['email_form']['email']['#default_value'] = 'New value!';
    $variables['content']['email_form'] = show(drupal_get_form('comment_email_form'));
    dsm($variables);
}
/**
 * Создаем форму, которая будет хранить данные email адресов бригад и отправлять письмо.
 **/
function comment_email_form($form, &$form_state){
$query = db_select('comment', 'c')
    ->fields('c', array('cid', 'nid'));
$result = $query->execute();
$comments = array();
foreach($result as $value){
    $comments[$value->cid] = comment_load($value->cid);
 }
  $form['email'] = array(
    '#type' => 'textfield',
    '#access' => TRUE,
    '#default_value' => 'test123',
    '#required' => TRUE,
  );

  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Send'),
  );

  $form['#validate'][] = 'comment_email_form_validate';
  $form['#submit'][] = 'comment_email_form_submit';
  return $form;
}

Thanks for any help.
Answer: You pass extra arguments when building the form using the drupal_get_form.
For example:
drupal_get_form('comment_email_form', 'default_value');

function comment_email_form($form, &$form_state, $default_value)
{
    // $default_value is here the string 'default_value' value passed as extra argument
    // ... rest of your form
}

Comment: but on the contrary I need to pass the value of preprocessing functions
Comment: In your preprocess function, where you retrieve the form, you can call show(drupal_get_form('comment_email_form', 'New value!'));
Comment: oh yeah, thank you, it works. very grateful for your help :)


Teste de validação funciona com valores numéricos, mas não com strings

Question: Meu código de herança funciona normal, o que eu queria fazer é que caso o nome e o pseudonimo sejam null o código pararia, o código só para de executar quando idade, altura ou peso são null.
import 'dart:io';

main() {

  var humano = Humano();
  var pessoa = Pessoa();

  stdout.write("Digite o seu nome: ");
  pessoa.nome = stdin.readLineSync();
  if (pessoa.nome == null) return;
  stdout.write("Digite o seu pseudônimo: ");
  pessoa.pseudonimo = stdin.readLineSync();
  if (pessoa.pseudonimo == null) return;
  stdout.write("Digite a sua idade: ");
  pessoa.idade = int.tryParse(stdin.readLineSync());
  if (pessoa.idade == null) return;
  stdout.write("\n");

  stdout.write("Digite o seu peso: ");
  humano.peso = double.tryParse(stdin.readLineSync());
  if (humano.peso == null) return;
  stdout.write("Digite o sua altura: ");
   humano.altura = double.tryParse(stdin.readLineSync());
  if (humano.altura == null) return;
  stdout.write("\n");

  print("Nome: ${pessoa.nome}");
  print("Idade: ${pessoa.idade}");
  print("Pseudônimo: ${pessoa.pseudonimo}");
  print("Altura: ${humano.altura}cm");
  print("Peso: ${humano.peso}kg");

}

class Humano {

  double peso;
  double altura;

  Humano({this.peso, this.altura});

}

class Pessoa extends Humano {

  String nome;
  String pseudonimo;
  int idade;

  Pessoa({this.nome, this.pseudonimo, this.idade});

}

Answer: Antes de tudo, vamos notar algumas coisas.
Não são necessários dois objetos, quando um pertence a uma subclasse do outro
De acordo com o que você colocou na pergunta, a classe Pessoa herda (estende) da classe Humano – além disso, não sei se é realmente necessária essa classe.
Se, de fato, ela herda, então, não é necessário você criar um objeto de Pessoa e um objeto de Humano para poder utilizar os membros de cada uma, já que a primeira deveria ter os membros da segunda!
O que parece que está acontecendo, é que você não está chamando o construtor da superclasse de Pessoa (a classe Humano). Ou seja, apesar de você herdar da classe, você não pede para ela tratar os dados que são cabíveis a ela.
Para isso, você utiliza o comando super, que (em diversas linguagens) serve exatamente para chamar o construtor da superclasse (classe-mãe) de uma classe.
class Humano {

  double peso;
  double altura;

  Humano({this.peso, this.altura});
}

class Pessoa extends Humano {

  String nome;
  String pseudonimo;
  int idade;

  Pessoa({double peso, double altura, this.nome, this.pseudonimo, this.idade})
    : super(peso: peso, altura: altura);
}

Ou seja, eu pego os parâmetros peso e altura e passo para o construtor da classe que irá lidar com eles, ou seja, o construtor da [super]classe Humano!
Obtendo os dados primeiro e criando o objeto depois
Outra coisa que poderíamos modificar, é que ao invés de você criar o objeto "vazio" e preencher os seus campos à medida que vai pedindo ao usuário – o que parece um pouco com o que, às vezes, se faz com as structs em C – na minha opinião, poderia ficar melhor se você obtivesse esses dados primeiro, e depois passasse-os para o construtor da classe Pessoa:
main() {
  double peso, altura;
  String nome, pseudonimo;
  int idade;

  stdout.write("Digite o seu nome: ");
  nome = stdin.readLineSync();

  stdout.write("Digite o seu pseudônimo: ");
  pseudonimo = stdin.readLineSync();

  stdout.write("Digite a sua idade: ");
  idade = int.tryParse(stdin.readLineSync());

  stdout.write("Digite o seu peso: ");
  peso = double.tryParse(stdin.readLineSync());

  stdout.write("Digite a sua altura: ");
  altura = double.tryParse(stdin.readLineSync());

  stdout.write("\n");

  var pessoa = new Pessoa(
    peso: peso,
    altura: altura,
    nome: nome,
    pseudonimo: pseudonimo,
    idade: idade
  );

  print("Nome: ${pessoa.nome}");
  print("Idade: ${pessoa.idade}");
  print("Pseudônimo: ${pessoa.pseudonimo}");
  print("Altura: ${pessoa.altura}cm");
  print("Peso: ${pessoa.peso}kg");
}

Pois, assim, você tanto estará fazendo o uso apropriado do construtor, como também poderá deixar o código um pouco mais "organizado", através ainda da próxima sugestão.
Validando os dados dentro da classe
Pedindo os dados primeiro e criando o objeto depois, dá margem para que você faça a validação dos dados na própria classe!
Na minha perspectiva, eu acho que isso também é o melhor a se fazer, pois a classe será a responsável por estabelecer as "regras", da mesma forma que numa espécie de estrutura MVC, a camada Model é a responsável pelas regras de negócio. Entretanto, ao final, apresentarei uma pequena desvantagem da utilização desse método.
Mas, vamos à solução do problema!
Resolvendo o real problema
Quando você usa a função stdin.readLineSync, ela irá retornar uma string! Portanto, se você não digitar nada, ao invés de retornar null, ela retornará uma string vazia ("").
Já o método estático int.tryParse, ao tentar converter o valor que lhe foi passado, seu retorno pode ser um inteiro (int), ou null, o último quando a conversão não foi bem-sucedida. Do mesmo modo, o método estático double.tryParse (só que, ao invés de int, retorna um double).
E com isso, descobrimos o porquê de o teste de null para idade, altura e peso dar certo: pois, quando o usuário não digita nada, a string vazia é convertida por esses métodos para null!
Por isso, para validar os dados que são strings, nós devemos utilizar as propriedades que servem exatamente para saber se uma string é vazia, ou não. São elas: String#isEmpty e String#isNotEmpty.
Assim, agora com o objetivo de fazer a validação na classe, nós podemos optar por utilizar técnicas manuais, dessa forma:
class Humano {

  double peso;
  double altura;

  Humano({this.peso, this.altura}) {
    if (peso == null || altura == null) {
      throw new Exception("os campos 'peso' e 'altura' não devem ser nulos!");
    }
  }
}

class Pessoa extends Humano {

  String nome;
  String pseudonimo;
  int idade;

  Pessoa({double peso, double altura, this.nome, this.pseudonimo, this.idade})
    : super(peso: peso, altura: altura)
  {
    if (nome.isEmpty || pseudonimo.isEmpty || idade == null) {
      throw new Exception("os campos 'nome', 'pseudonimo' e 'idade' não devem ser nulos ou vazios!");
    }
  }
}

Ou então, podemos optar por utilizar comandos fornecidos pela própria linguagem, como o comando assert, sobre o qual você pode saber mais nesse post!
Com ele, o código poderia ficar ainda menor:
class Humano {

  double peso;
  double altura;

  Humano({this.peso, this.altura})
    : assert(peso != null && altura != null,
             "os campos 'peso' e 'altura' não devem ser nulos!");
}

class Pessoa extends Humano {

  String nome;
  String pseudonimo;
  int idade;

  Pessoa({double peso, double altura, this.nome, this.pseudonimo, this.idade})
    : assert(nome.isNotEmpty && pseudonimo.isNotEmpty && idade != null,
             "os campos 'nome', 'pseudonimo' e 'idade' não devem ser nulos ou vazios!"),
      super(peso: peso, altura: altura);
}

OBS.: quando você utilizar outros comandos de inicialização junto com o super, com essa sintaxe, sempre coloque o super por último! Caso contrário, irá gerar um erro!

Em ambos os códigos, fazemos com que:

A classe Pessoa garanta que os dados de nome e pseudonimo não sejam vazios, e o dado de idade não seja null;
A classe Humano garanta que os dados de peso e altura não seja null.

Porém, no segundo caso, você tem que se atentar ao que é dito naquela resposta – sobre a ativação do comando assert – pois, caso esteja desativado, a validação não terá efeito!

No final de tudo, o seu código deve ficar assim:
Forma com validação manual
import "dart:io";

main() {
  double peso, altura;
  String nome, pseudonimo;
  int idade;

  stdout.write("Digite o seu nome: ");
  nome = stdin.readLineSync();

  stdout.write("Digite o seu pseudônimo: ");
  pseudonimo = stdin.readLineSync();

  stdout.write("Digite a sua idade: ");
  idade = int.tryParse(stdin.readLineSync());

  stdout.write("Digite o seu peso: ");
  peso = double.tryParse(stdin.readLineSync());

  stdout.write("Digite a sua altura: ");
  altura = double.tryParse(stdin.readLineSync());

  stdout.write("\n");

  var pessoa = new Pessoa(
    peso: peso,
    altura: altura,
    nome: nome,
    pseudonimo: pseudonimo,
    idade: idade
  );

  print("Nome: ${pessoa.nome}");
  print("Idade: ${pessoa.idade}");
  print("Pseudônimo: ${pessoa.pseudonimo}");
  print("Altura: ${pessoa.altura}cm");
  print("Peso: ${pessoa.peso}kg");
}

class Humano {

  double peso;
  double altura;

  Humano({this.peso, this.altura}) {
    if (peso == null || altura == null) {
      throw new Exception("os campos 'peso' e 'altura' não devem ser nulos!");
    }
  }
}

class Pessoa extends Humano {

  String nome;
  String pseudonimo;
  int idade;

  Pessoa({double peso, double altura, this.nome, this.pseudonimo, this.idade})
    : super(peso: peso, altura: altura)
  {
    if (nome.isEmpty || pseudonimo.isEmpty || idade == null) {
      throw new Exception("os campos 'nome', 'pseudonimo' e 'idade' não devem ser nulos ou vazios!");
    }
  }
}

Forma com validação com assert
import "dart:io";

main() {
  double peso, altura;
  String nome, pseudonimo;
  int idade;

  stdout.write("Digite o seu nome: ");
  nome = stdin.readLineSync();

  stdout.write("Digite o seu pseudônimo: ");
  pseudonimo = stdin.readLineSync();

  stdout.write("Digite a sua idade: ");
  idade = int.tryParse(stdin.readLineSync());

  stdout.write("\n");

  stdout.write("Digite o seu peso: ");
  peso = double.tryParse(stdin.readLineSync());

  stdout.write("Digite o sua altura: ");
  altura = double.tryParse(stdin.readLineSync());

  stdout.write("\n");

  var pessoa = new Pessoa(
    peso: peso,
    altura: altura,
    nome: nome,
    pseudonimo: pseudonimo,
    idade: idade
  );

  print("Nome: ${pessoa.nome}");
  print("Idade: ${pessoa.idade}");
  print("Pseudônimo: ${pessoa.pseudonimo}");
  print("Altura: ${pessoa.altura}cm");
  print("Peso: ${pessoa.peso}kg");
}

class Humano {

  double peso;
  double altura;

  Humano({this.peso, this.altura})
    : assert(peso != null && altura != null,
             "os campos 'peso' e 'altura' não devem ser nulos!");
}

class Pessoa extends Humano {

  String nome;
  String pseudonimo;
  int idade;

  Pessoa({double peso, double altura, this.nome, this.pseudonimo, this.idade})
    : assert(nome.isNotEmpty && pseudonimo.isNotEmpty && idade != null,
             "os campos 'nome', 'pseudonimo' e 'idade' não devem ser nulos ou vazios!"),
      super(peso: peso, altura: altura);
}

Conclusão
Um ponto, porém, que faz o programa agir de forma diferente, é que a validação só será feita quando todos os dados tiverem sido preenchidos. Ou seja, o usuário não terá um retorno imediato sobre a validade daquele dado inconsistente que ele forneceu.
Apesar disso, agora, o funcionamento do programa estará da forma que (acho que) se espera e ainda com um código, na minha opinião, um pouco melhor separado e "organizado"!
Outra coisa também sobre a qual poderia ter falado na resposta, mas que optei por não fazê-lo, é sobre o novo sistema de tipos com null-safety do Dart. Ele mudaria muito o jeito que você escreveria esse código! Só que, como ele ainda não é obrigatório, então não quis fazer cobertura sobre ele agora. Mas, quem sabe, no futuro, eu possa adicionar algo sobre isso! :)
Comment: Interessante sua explicação, obrigado.


How to force cron to use config saved during a SimpleTest?

Question: I write a test using Drupal\simpletest\WebTestBase for a custom module, which implements hook_cron(). The test saves a configuration object, which should be used by the cron, and then runs the cron:
<code>function testCron()
{
    $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
    $config
      ->set('some_setting', 'some value')
      ->set('another_setting', 'another value');
    \Drupal::service('cron')->run();
}
</code>
The settings are saved and can be used during the test. But when I want to use them in the cron (in mymodule.module):
<code>/**
 * Implements hook_cron().
 */
function mymodule_cron()
{
    $config = \Drupal::config('mymodule.settings');
    ...
}
</code>
then instead of the saved values, the default settings from config/import/mymodule.settings.yml are used.
How can I force the cron to use the settings saved in the test?
Comment: Actually, I take that back. Your example is missing the save() call?
Comment: You already posted a bunch of related questions, which all essentially result from something going very very wrong. What you're describing should simply not happen, but I'm not sure if it can be answered, would more likely need to be debugged on your system.
Comment: You are right. I started a new job and write tests for a bunch of Drupal custom modules. I have wrote a lot of tests in Yii2/Codeception, but testing in Drupal is quite different... I have no save() call in the test. I will add it to the  test as soon as I'm in my office (on Tuesday). Thanks.
Comment: The save() call is the correct solution. I just added '->save()' after '->set('another_setting', 'another value')'. Would you prefer to write the answer, or should I write it? Thanks.
Answer: As commented, you were missing the save call in the test.
That means that the change is only in the runtime object returned by getEditable() and since get() and getEditable() do not share the static cache, you didn't see the change.


Intersection theory and blow-ups

Question: Surely a silly question, but anyway. Suppose I blow up a point $P$ in the plane. Then the exceptional divisor $E$ should have zero intersection with (the strict transform of) any curve in the plane, since they are all linearly equivalent to a line not passing through $P$. But the strict transform of a line $L$ through $P$ seems to be a line which intersects $E$ transversely (if I've computed correctly) which would mean $L \cdot E=1$. What have I done wrong?
Answer: This just means that the pull-back process doesn't preserve linear equivalence of divisors. This would work if we had a flat morphism.
Comment: Thanks! I just realised that too - it *was* a silly question :)
Comment: Maybe "strict transform" is a better word than pull-back. The canonical map $\operatorname{Pic}(X) \to \operatorname{Pic}(\widetilde X)$, which "pulls-back" the line bundle, certainly preserves linear equivalence, if we identify line bundles with divisors modulo linear equivalence.
Answer: The exceptional divisor intersects trivially the total transform of a curve in the plane, not the strict transform.
Comment: True. This is because pulling-back invertible sheaves is well defined for any morphism. The strict transform is the pull-back of cycles, the total transform is the pull-back of invertible sheaves.

Intersection theory and blow-ups


Given 4 distinct rooms, in how many ways do 8 students occupy these rooms and no room is empty?

Question: There are 4 distinct rooms and  8 (distinct) students. Each student must occupy a room and no room is empty. How many arrangement is possible?
My attempt

First fill each room with one student to make sure there is no empty room. There are $P(8,4)=\frac{8!}{4!}$ ways. There are 4 students left for the next steps.

For the remaining 4 students, there are $4^4$ ways.

The total is  $\frac{8!}{4!}\times 4^4 = 430 080$ ways which is not the same as the key of 40824.

Could you tell me how to solve this problem? As it is for high school students, I don't think we need generating function, right?
Comment: As an aside, the answer could be written more succinctly using [stirling numbers of the second kind](https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind), there being $4!\left\{\begin{smallmatrix}8\\4\end{smallmatrix}\right\}$ ways.
Comment: @JMoravitz: Thank you! A nice info.
Answer: Your approach is incorrect since filling each room first and then filling the rooms with the remaining students over counts since each distribution in which more than one student is assigned to a room is counted multiple times, once for each way of designating one of the students in the room as the student who is assigned to that room.
If there were no restrictions, we would have four choices for each of the eight students, so there are $4^8$ possible distributions of students to rooms.  From these, we must subtract those distributions which leave one or more rooms empty.
There are $\binom{4}{k}$ ways to leave exactly $k$ of the rooms empty and $(4 - k)^8$ ways to distribute the eight students to the remaining $4 - k$ rooms.  By the Inclusion-Exclusion Principle, the number of ways eight students can be distributed to four rooms so that no room is left empty is
$$\sum_{k = 0}^{4} (-1)^k\binom{4}{k}(4 - k)^8 = 4^8 - \binom{4}{1}3^8 + \binom{4}{2}2^8 - \binom{4}{3}1^8 + \binom{4}{4}0^8$$
Comment: This calculation only involves a finite number of steps.  \begin{align*} 4^8 - \binom{4}{1}3^8 + \binom{4}{2}2^8 - \binom{4}{3}1^8 + \binom{4}{4}0^8 & = 4^8 - 4 \cdot 3^8 + 6 \cdot 2^8 - 4 \cdot 1^8 + 0\\ & = 65,536 - 4 \dot 6561 + 6 \cdot 256 - 4 \cdot 1\\ & = 65536 - 26244 + 1536 - 4\\ & = 40824 \end{align*}


haystack elasticsearch facet but disregard filters on this query

Question: Using haystack solr I can do this:
<code># facet by category but disregard any category filters on this query
squeryset = squeryset.facet('{!ex=category}category')
</code>
which will give me facets for the category but ignore any category filters
Now how do I do the same query using elasticsearch?
It's for when someone queries for something with a specific category, I can show the counts for the other categories they did not select.
Answer: I was looking for the same thing. See http://demo.fullscale.co/multiselect/ for a working demo to do this in ES. It is however not supported by Haystack. I'm working on that to make it work.
Paul
Comment: Hi Paul, did you make any progress on making this work for ES? We are looking for something similar
Comment: Hi @PaulBormans im looking for similar solution. please can you post the solution here.
Comment: I should write a blog on this subject and post the link here... give me some time to do this.
Paul
Comment: Please see http://paulbormans.blogspot.nl/p/multi-select-faceting-with-django.html for a write-up of the solution that is working for me with the source code.


Is there something analogous to dropout for classification problems?

Question: I have only heard about dropout being applied to training of neural networks. Could the same technique, in theory, be applied to any iterative ML algorithm? For example, in mini-batch training, each mini-batch iteration could randomly drop out some arbitrary features. Has this been tried for, say, logistic regression with SGD optimization? Any thoughts/opinions appreciated.

Wager et al. seem to follow the approach I suggested in the OP:
http://papers.nips.cc/paper/4882-dropout-training-as-adaptive-regularization.pdf
Comment: Dropout algorithms also exist for [gradient boosting trees](https://arxiv.org/pdf/1505.01866.pdf).
Answer: One simplest example of dropout being used in other algorithms is random forest: At each step of random forest, you randomly select only several of the features to split your trees, this is totally equivalent to randomly dropping out some of the features as in neural network.
Comment: This is an imperfect analogy though. While feature selection in random forests is random, you ultimately settle on features and splits that provide some minimal gain in accuracy. Whereas with dropout, you will keep all your neurons.
Comment: @AlexR. I partially agree. I think the similarity is stronger than you put here. If you have a large number of trees in random forest, it is highly probable that those not-so-useful features are still used in some of the trees at some splitting, so you still keeps all your "neurons" in random forest, but these not-so-useful features are not used as often as others.
Comment: +1. To your point though, what you describe with random forests is somewhat more related to DropConnect where you dropout weights in individual neurons. For ensembles of random forests, the analogy of dropout would be to random drop out entire trees and use the remaining ones to compute the output (as an average, for example)
Comment: @AlexR. Completely agree with you on this.


Spring-Hibernate integration : Unable to persist

Question: I'm trying to use hibernate in spring framework.
Following are my files :
Employee.java :
package com.springstarter;

    public class Employee
    {
        private int id;

        private String name;

        private float salary;

        public Employee()
        {
        }

        public Employee( int id, String name, float salary )
        {
            super();
            this.id = id;
            this.name = name;
            this.salary = salary;
        }

        public int getId()
        {
            return id;
        }

        public void setId( int id )
        {
            this.id = id;
        }

        public String getName()
        {
            return name;
        }

        public void setName( String name )
        {
            this.name = name;
        }

        public float getSalary()
        {
            return salary;
        }

        public void setSalary( float salary )
        {
            this.salary = salary;
        }

    }

EmployeeDao.java

    package com.springstarter;

    import java.util.ArrayList;
    import java.util.List;

    import org.springframework.orm.hibernate3.HibernateTemplate;

    public class EmployeeDao
    {
        HibernateTemplate template;

        public void setTemplate( HibernateTemplate template )
        {
            this.template = template;
        }

        public void saveEmployee( Employee e )
        {
            template.save( e );
        }

        public void updateEmployee( Employee e )
        {
            template.update( e );
        }

        public void deleteEmployee( Employee e )
        {
            template.delete( e );
        }

        public Employee getById( int id )
        {
            Employee e = ( Employee ) template.get( Employee.class, id );
            return e;
        }

        public List<Employee> getEmployees()
        {
            List<Employee> list = new ArrayList<Employee>();
            list = template.loadAll( Employee.class );
            return list;
        }
    }

Driver class :
package com.springstarter;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringORMApp
{
    public static void main( String[] args )
    {
        ApplicationContext ctx = new ClassPathXmlApplicationContext( "SpringStarter.xml" );
        EmployeeDao dao = ( EmployeeDao ) ctx.getBean( "edao" );
        System.out.println( ( ( Employee ) dao.getById( 1 ) ).getName() );
    }
}

Beans xml file :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
        <property name="url" value="jdbc:oracle:thin:@[10.113.49.82]:1521:roc12c" />
        <property name="username" value="milli_sec" />
        <property name="password" value="milli_sec" />
    </bean>
    <bean id="mysessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="mappingResources">
            <list>
                <value>employee.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="mysessionFactory"></property>
    </bean>

    <bean id="edao" class="com.springstarter.EmployeeDao">
        <property name="template" ref="template"></property>
    </bean>
</beans>

employee.hbm.xml file
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.springstarter.Employee" table="employee">
        <id name="id">
            <generator class="assigned"></generator>
        </id>
        <property name="name"></property>
        <property name="salary"></property>
    </class>
</hibernate-mapping>

No compilation issues.But expecting the employee object of id 1.
The following are the logs.
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jan 28, 2016 4:28:15 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Jan 28, 2016 4:28:15 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Jan 28, 2016 4:28:16 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Jan 28, 2016 4:28:46 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: MILLI_SEC.EMPLOYEE
Jan 28, 2016 4:28:46 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [id, name, salary]
Jan 28, 2016 4:28:46 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Jan 28, 2016 4:28:46 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [employee_pk]
Jan 28, 2016 4:28:46 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete

Comment: Try changing this property `"hibernate.hbm2ddl.auto"` from `update` to `validate` or remove it at all. Also, make sure to catch any exception in your application and log it properly.
Comment: Pls provide complete log
Answer: I think, the main issue that you don't use any transactions. For reading data with Hibernate you need transactions too. So you need to extend your SpringStarter.xml configuration with a transaction manager. You can use @Transactional annotation or add transactions to methods by methods masks in the SpringStarter.xml.
And there are some problems in your code
org.springframework.orm.hibernate3.HibernateTemplate
should be
org.springframework.orm.hibernate4.HibernateTemplate
public List<Employee> getEmployees()
{
    List<Employee> list = new ArrayList<Employee>();
    list = template.loadAll( Employee.class );
    return list;
}

should be
public List<Employee> getEmployees()
{
    return template.loadAll( Employee.class );
}

and
HibernateTemplate template;

should be
private HibernateTemplate template;


sed +append number after last matched word in line

Question: I have log file called: log.txt
my target is to add the parameter: $PARAM only after the last string: "Number" in the file log.txt

remark: PARAM could be any number

example:
 PARAM=34.43435454

tail -10 log.txt
   date 12.3.2010 Number 2.34
   date 12.3.2010 Number 2.14
   date 12.3.2010 Number 34.43435454

someone have idea how to do that with sed?
Comment: I really don't understand what you want to do. Could you please post an example of the log file before your supposed edit? Also, where does the different numbers come from and how do you want to decide which numbers goes where? Or do you simply want to edit the last line, appending the number (i.e. 34.4343...)?
Comment: the target was to add $PARAM value after the last "Number" word in the file , if for example I have 23 Number words then need to append the $PARAM after "Number" word
Answer: After "Number" on every line:
sed "s/.*Number/& $PARAM/" log.txt

After "Number" on the last line:
sed "\$s/.*Number/& $PARAM/" log.txt

After "Number" the last time it appears in the file:
sed "/Number/!b;:a;\$!N;/\n.*Number/{h;s/\n[^\n]*\$//p;g;s/^.*\n//};\$!ba;s/^\(.*Number \)/\1$PARAM/" log.txt

Explanation of the last version:

/Number/!b - if the line doesn't contain "Number" branch to the end of the script and print the line
:a - loop label "a"

\$!N - if it's not the last line of the file, append the next line to the end of the contents of pattern space
/\n.*Number/{ - if pattern space includes "Number" after a newline then

h - copy pattern space to hold space
s/\n[^\n]*\$//p - delete the part after the newline and print the remainder
g - copy hold space to pattern space
s/^.*\n//} - delete the part before the newline, end if

\$!ba - branch to label "a"
s/^\(.*Number \)/\1$PARAM/ - add the contents of the variable after "Number"
Comment: hi little problem the sed actually add the $PARAM number but also delete the word  "Number" from the file  , how to fix that?
Comment: @klod: Please see my edited answer. I moved the `\\)` and a space plus fixed a couple of typos.


Finding IP Of Remote Host Machine By IP Of Guest Machine

Question: I am trying to find a way to figure out on which of the servers the virtual machine actually is residing. I know the ip of the virtual machine. It is in a bridged mode on the local network inside one of the Ubuntu servers. The problem is I don't know which one.
I obtained mac and IP of the machine using arp-scan. Is there some sort of utility that could show me the route that arp takes through the local network, so I could capture the mac or ip of the server on which the actual VM is located?
Answer: The general approach to solving this problem would be to interrogate the hosts rather the VMs. The VMs in theory have no idea that they are VMs.
To that end, assuming virtualbox, the command VBoxManage list runningvms on a given host should display all running VMs on that host.  Other hypervisors might provide a similar scripting capability.

If you NEED a purely networking solution to the problem you will need some pretty fancy switches (think cisco and the like - not consumer stuff). A managed switch should allow you to see all mac addresses coming from a given port. Simply map the ports to the hosts they are attached to and then find the MAC on the switch.
This is how our network admin tracks down our roaming VMs since he does not have access to the VMWare environment.

And the long story short is: You can't get this information from the guest you have to interrogate something higher up on the chain like the host or the switch port.
Comment: Thanks, I have a fortigate 60C, so will try to see if there is such functionality.
Answer: No. There is no way of doing this*.
There is no such thing as a route for arp. It's locally-significant only.
*... unless you control the virtualization layer in such a way that you can push that information into the guests.
Answer: No.
At an organizational level, you need to have an inventory of this kind of thing.  For a developer and his one or two hypervisors with virtual machines that don't have any production significance, it's fine to have VMs all over the place ad hoc.  That is not OK in a managed environment.  How do you know what will be affected by a hypervisor reboot for patches or hardware maintenance?  How do you know how much free capacity you have and whether your hardware loads are appropriately balanced?  Either you must manage this manually, or you must use software that manages it ("cloud").
Make an inventory by querying each hypervisor for the VMs running in it, and their hostname, network address, purpose, and other pertinent information.  Then, you will have your answer, both now and later.


Why doesn't penalized cubic regression reduce the number of knots in a GAM?

Question: As far as I understand, cubic regression penalization prevents overfitting by reducing the number of knots by penalizing wiggliness. The supplied parameter k serves only as a starting points for choosing the knots.
From ?mgcv::choose.k:

In practice k-1 (or k) sets the upper limit on the degrees of freedom associated with an s smooth [...] However the actual effective degrees of freedom are controlled by the degree of penalization selected during fitting, by GCV, AIC, REML or whatever is specified.

However, with my model specifications, penalization does not seem to have an effect. The demo below starts and ends with 114 knots. Obviously I'm mistaken somewhere. What am I missing?
> require(mgcv)
> data(beavers)
> mod <- gam(temp ~ s(time, bs="cr", k = length(beaver1$time)), data = beaver1)
> length(mod$smooth[[1]]$xp)
[1] 114
> plot(mod, scheme = 1, residuals = T)

Comment: What do you mean that it "starts and ends" with 114 knots? You're fitting a model that has 114 coefficients (including intercept); I don't see how there's a "start" or an "end". The penalization is working, but you're fitting the response to a temporal predictor that's sampled very finely as compared to the oscillations of the response, so it's basically just generating an interpolant.
Answer: You do have a slight misunderstanding of how penalization works in the spline regression situation.  Regression with (cubic, in this case) splines does not implement penalization by reducing the number of knots, but instead by reducing the magnitude of the coefficients of the spline terms.  "Degrees of freedom" doesn't refer to the number of knots, but rather to "actual effective degrees of freedom", which take into account the fact that the regression wasn't allowed to fully optimize on the coefficients (unlike, say, least squares), therefore the effective loss in degrees of freedom is somewhat less than the number of coefficients estimated.
One way of writing out the regression problem is:
$$\min_{\beta} \sum(y_i- Z_i^T\gamma - X_i^T\beta)^2 + \lambda||\beta||_2$$
The $X_i$ are the cubic spline terms, the $Z_i$ are terms whose coefficients aren't being regularized.  The last term is a penalty on the magnitude of the $\beta$ coefficients; the larger $\lambda$ is, the more the coefficients are shrunk towards zero.  It's this last term that penalizes "wiggliness"; to see this, imagine what happens as $\lambda \rightarrow \infty$ - the fitted curve comes closer and closer to ignoring the $X_i$ altogether, which is about as non-wiggly (with respect to the $X_i$) as you can get - it's saying that the estimated function is constant with respect to changes in the $X_i$.
You certainly could regularize by reducing the number of knots, but, from an optimization perspective, this is very difficult.  If you are optimizing with respect to knots, not only do you have to choose the number of knots but also their location.  As far as I know, there is no good, fast solution to the latter problem.  With regularization of the coefficients, there are high-quality approximations and shortcuts that are very effective at speeding up the computations.
Comment: I'd call it a fundamental misunderstanding on my behalf. Thanks for being so polite and the nice explanation.


How to show a field in views only when a checkbox is ticked?

Question: I want the user to be able to choose whether to show a description or not for each node in the view. Adding the filter only works on the entire object, I just want to show/hide one field. How can I achieve this?
Comment: what code have you tried? Take this question and strip "Drupal" from it. You have a listing and you want to toggle a  as shown or not-shown. Javascript can propbably do this. You probably want to look at the Form API, hook_form_alter() and the `#states` FAPI element in the Drupal API. Or, just just custom jQuery on the page ...
Comment: @Sergo, when you say you 'want the user to be able to choose' do you mean that you want to toggle between showing all description fields (where present) and hiding all description fields, using a toggle / dropdown akin to the normal Views exposed filters. Or do you mean that the user (who is editing the node) needs to be able to tick a box to make some text appear or not when the node is shown in a listing (my interpretation for the answer I've given). Or something else again?
Answer: You can do this with Views out of the box. No need for Views PHP here.

Add your boolean field in Views. (This assumes the default boolean set up, i.e. 0 for not checked and 1 for checked.)
Use the Key formatter - this isn't obvious, but I couldn't get it to work without this.
Select REWRITE RESULTS and put the description you want in there. This can include tokens so you can grab material from other fields in the node if that's what you need.
On NO RESULTS BEHAVIOR check all the boxes (Count the number 0 as empty, Hide if empty, Hide rewriting if empty)
Answer: You should be able to accomplish this with th Views PHP module.
Set up your view with the checkbox and description fields included but not visible. Then include a Global:PHP field, and under the field configuration put something like:
<code><?php
echo ($row->checkbox) ? $row->description : '';
?>
</code>
in the Display box.
Comment: ["While this module allows you to directly use PHP inside views which may be useful for quick and easy solutions, it is **highly advisable** to use regular handlers and plugins when available (or even to create one yourself). Take note that filtering and sorting a view using PHP always has a considerable perfomance impact."](https://www.drupal.org/project/views_php)


Como retirar formatação do comando GETDATE()

Question: Estou desenvolvendo uma aplicação que será usada por vários clientes simultaneamente, gostaria de utilizar como id o Dia, Mes, Ano, Hora, Minuto, Segundo e Milissegundo, teria como eu retirar as / e : que a função GETDATE() retorna?
Answer: Para o SQL Server a partir do 2012, use o FORMAT()
SELECT FORMAT( GETDATE(), 'yyyyMMddHHmmssfff' );

Veja os padrões de caracteres de formato de data aqui.
Answer: Se for SQL-SERVER 2008 ou anterior, a função FORMAT, muito bem aplicada pelo amigo @gmsantos não irá funcionar; Você pode fazer essa função para remover caracteres especiais:
CREATE FUNCTION [dbo].[fn_StripCharacters]
(
    @String NVARCHAR(MAX),
    @MatchExpression VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    SET @MatchExpression =  '%['+@MatchExpression+']%'

    WHILE PatIndex(@MatchExpression, @String) > 0
        SET @String = Stuff(@String, PatIndex(@MatchExpression, @String), 1, '')

    RETURN @String

END

Logo depois é só executar a query com a função, lembrando só de converter o resultado do GETDATE():
SELECT dbo.fn_StripCharacters(CONVERT(VARCHAR, GETDATE(), 120), '^a-z0-9')

O resultado será: 20150528095612
Fonte: SOen
Comment: Bem observado ;)


Strings: X^0 confusion

Question: I've been given the set of string:
                                X = {2,00}.

I've been asked to perform various concatenation operations on it.
For example; X^3 - Which I put: X^3 = XXX = {(2,00),(2,00),(2,00)}

and so on.
One of the questions is: X^0 (that looks dodgy, that's X to the power of zero)
To my knowledge anything which is ^0 = 1. So my answer is that
 X^0 = X = {2,00}

But my friend says it's an empty string?
X^0 = null = {}

Could anyone tell me who's right, if either, and more importantly why?
Many thanks
Comment: Empty or null string, not set.
Comment: You call $X$ a string, but the way you write it suggests you mean a *set* of strings.  Which one is it?
Comment: @ErickWong Sorry my mistake. A set of strings. I see you said my value for X^3 is wrong? How so?
Comment: @Fendorio I'd say that $\{(2,00),(2,00),(2,00)\}$ looks like the set containing just the ordered pair $(2,00)$ three times.  Where is the concatenation?
Comment: @ErickWong I can see where you're coming from, albeit from a basic point of view. How would you express X^3 in that case? With X = {2,00} Thankyou for your time btw :)
Comment: @Fendorio Can you name one string that belongs to $X^3$?  There are $8$ in total.
Comment: @ErickWong {(00),(2),(00,2)...} Am I on the right lines?
Answer: Usually, in a monoid, we define $x^0$ to be the identity element of the monoid, that is, the element $e$ such that $ex = x = xe$ for all $x$. This is so that the standard "exponent rules" such as $x^{a+b} = x^a \cdot x^b$ hold even when $a$ or $b=0$. In your case, since the operation is concatenation, it makes sense for $x^0$ to mean the empty string, since concatenating nothing does nothing.
More generally, given any starting set, the construction of words on that set by concatenation is called a free monoid.
Answer: As you said, for any $x$, $x^0=1$.
What is said here is actually that an element of a set to the power $0$ is the neutral element of this set for the "product" operation.
In your case the set is the set of strings and the "product" operation is concatenation. Thus the neutral string is the string which, when you concatenate it with another string is still equal to this other string. If you call this string $N$ (for neutral :)), you have for any string $X$:
$$N\times X=X\times N=X$$
In your case this string $N$ is the empty string.
What you wrote is actually equivalent to saying that $x^0=x$ which is wrong, it is $x^1$ that equals $x$.
Comment: Thankyou! Will accept when timer allows :)
Comment: You're welcome! By the way, what I said is basically the same thing as what @Alex P. answered. If you want more info on the subject you should look at the link he provided ;)
Comment: Possibly this should be the set consisting of the empty string.  The question as written seems a bit ambiguous, as the value for $X^3$ fails to match any valid interpretation I can see.
Comment: @ErickWong Well yes possibly, I agree the question is a bit ambiguous.

Strings: X^0 confusion


Submeter um post com reload de apenas de uma div

Question: Tenho um form que desejo passar via POST, mas sem dar reload na página inteira, após o envio das informações, desejava que uma div desse reload no seu conteúdo, tenho o seguinte código:

O POST está sendo enviado, porém, não sei se o reload não está sendo feito, ou está sendo feito sem atualizar as informações com dados recebidos via POST. Segue a div:

    <?php var_dump($this->searchbyorganization); ?>

Está em um var dump apenas para debug. Utilizo do Zend Framework, então a lógica está em outra classe controladora.
Comment: Acredito q vc deva usar o *done* ou um *success* do AJAX para obter o resultado do post
Comment: Assim como você não fará um "reload" da div, você deverá reescrever seu conteúdo com o retorno do post ajax ou fazer uma nova requisição ajax depois da success de seu post.
Answer: Assim como indicado nos comentários não faça load, ao invés disso implemente o handler de sucesso com done ou success e nesse handler atualize o html da
 que interessa.
Exemplo:
$("#issuedButton, #expiredButton, #activeButton, #revokedButton").click(function(){
    var dataString = $("#searchByTime").serialize();
    $.ajax({
        type: "POST",
        url: "index",
        data: dataString
    }).done(function(dados){ //done em vez de load
        $("#reload").html(dados); //atribuir o conteúdo do div com a função html()
    });

    return false;
});

Note que estou a assumir que os dados enviados da página php já são o html atualizado a substituir no conteúdo da

Comment: Então, ele carregou o html inteiro da página dentro da div, o que eu queria, é que ele só desse um refresh na div, como acontece num submit.
Comment: @ViniciusMacelai A minha resposta funciona dessa forma. O ajax é assincrono e não força refresh, e não é feita a navegação no submit do formulário devido ao `return false;`. Depois o `$("#reload").html(dados)` recarrega apenas o div que quer
Comment: acho que entendi o que aconteceu, na variavel "dados" está toda página HTML, apenas mudei para isso $("#reload").html($(dados).find("#reload")); e funcionou, muito obrigado pela ajuda.


html email with tables send from plsql package and viewed in lotus notes

Question: I was trying to send html from oracle plsql package..the code worked and i received the email in lotus notes client.
But the html table gets shrunk when window size is changed in lotus notes.
Please help me what should i put in html code to avoid this..
In the table style, i had included table layout : fixed, cellpadding and cellspacing to zero also included max width and min width and max height and min height to lock the table from getting shrunk. Here is my code:

 Sl.no	 Date	 Item Name	 Number of items	 Delivery date

 1	 17 Nov 2016	 Battery	 11	 20 Dec 2016

But all of this fails in lotus notes 8.5.
Comment: You haven't shown your HTML or mentioned what version(s) of Lotus Notes you are targeting. It's very unlikely that anyone can help you without at least that much information.
Comment:

Sl.no
Date
Item Name
Number of items
Delivery date

1
17 Nov 2016
Battery
11
20 Dec 2016
Comment: Another item i noticed is when trying to forwarf the mail received using html,lotus notes shrinking it always to 7 inches.
Comment: Lotus Notes was first released more than 25 years ago. There are dozens of different versions in use. What version(s) have you tested this with.
Comment: Lotus notes 8.5
Answer: Sadly, I have not figured out a reliable way to get the Lotus Notes client to do style tags.[1] You could try the style attributes within each cell, but your best bet is to avoid CSS wherever possible and, however painful it may be, force your table width with a row like2

Where the source leads to the database's DelOptionSpacer.gif image resource (which is a clear gif in the 9.0 mail template... not sure about 8.5). You might be better off with a src of ="../../DelOptionSpacer.gif?OpenImageResource"
Other tips:

You are missing your
 tag at the end.
You might wish to consider using  tags instead of  tags in the first row.

I know Domino can be frustrating sometimes! I often tell people it's like building with Duplo blocks - you can get close to what you want VERY quickly but, often, it's not easy to get exactly what you want.

1 - Hopefully I'm wrong??? Anyone???
2 - untested
Comment: @Richard...is there any way to overcome the situation mentioned in my last comment


How To Make a Nullable Integer Value

Question: I'm just start to make an application. I got some textfield that must filled with integer value, but when the textfield is empty, I want the value is still null in database rather than must add "0".
it's something like this
        DR.IN = Me.txtIn.Text
        DR.OUT = Me.txtOut.Text

the two of that is integer value, that when i'm save to data base the error comes and said

The Nullable Object Must Have Value

I must add "0", but I want the data is still null. Do anyone know how to do that?
thanks for your help and sorry for really bad grammar, I hope someone out there would understand my question :)
Comment: What is `DR.IN` and `DR.OUT`? Where is the error raised?
Comment: Me.txtIn.Text != nothing then Me.txtIn.Text else nothing.But make sure `DR.IN` and `DR.OUT` are nullable ints.Something like Dim DR.IN? as int
Comment: @TimSchmelter it's class that I made
Comment: @AmitKumarGhosh uumm.. I'm not sure I understand that, sorry
Comment: @Matt has come up with what I meant.
Comment: @AmitKumarGhosh oh, I'm really sorry, because I'm new in vb.net
Answer: You can just do a conditional check using the If Operator to return either Nothing (null) if there is no text in the textbox or the integer value of the textbox:
Dim value As Integer? = If(TextBox1.Text.Length = 0, Nothing, Integer.Parse(TextBox1.Text))

Comment: hey, yeah! this is all I need. Thank's so much!
Answer: You haven't shown some rather important information but I'm going to assume that you are using the Value property of your Integer? without first checking whether it actually has a value.  That's the whole point of a Nullable: it can have a value or not.  You can't use the value if there isn't one.  Saving an Integer? might look like this:
Dim command as new SqlCommand

command.CommandText = "UPDATE MyTable SET Number = @Number WHERE ID = @ID"

command.Parameters.Add("@Number", SqlDbType.Int).Value = If(myNullableInteger.HasValue,
                                                            myNullableInteger.Value,
                                                            CObj(DBNull.Value))

Answer: You can make a nullable integer in C# like :
int? myint;

and in VB.net like:
Dim myint As Integer?

Answer: Using default(Nullable<type>) will return you a Nullable<type> set to null.
Comment: that's okay, also my bad to add C# tag, that I don't even remember I've add that tag xD
Comment: My bad... Question was flagged C# initially. I'm no VB.Net expert :$

How To Make a Nullable Integer Value