Conditional Distribution in logistic regression

Question: In a logistic regression, given that  $\pi_i=Pr(Y_i=1|X_i=x_i)=\dfrac{\text{exp}(\beta_0+\beta_1 x_i)}{1+\text{exp}(\beta_0+\beta_1 x_i)}$, is it correct to say that logistic regression assumes that the conditional distribution $f(Y|X) \sim  Logistic$?
Comment: @Glen_b You're right, cf. [Latent variable interpretation](https://en.wikipedia.org/wiki/Logistic_regression#Latent_variable_interpretation)
Comment: The assumed distribution in logistic regression is **binomial**. $f(Y_i|X_i = x_i) \sim B(1, \pi_i(x_i))$
Comment: The logistic distribution doesn't have much to do with logistic regression - except that the link function is the same as the CDF for $\mu=0, s=1$ (wikipedia notation)
Comment: @AlexR Actually, there is a connection to the logistic distribution.
Comment: Thanks for the response. Does the logistic distribution only apply to the errors then? It just seems intuitive that because we estimate probabilities using a logistic function, this follows from the conditional being logistically distributed- do you see where I am coming from?
Answer: I am going to flesh out some of the comments to this post into an answer (with thanks to Glen_b and AlexR for their excellent comments).  The first thing to note is that the response variable in a logistic regression is binary, with allowable values $y_i = 0,1$, so any distribution that does not accord with that support is incorrect.  The distribution for the response variable in a logistic regression is Bernoulli, with a logistic mean.

Response distribution: The response distribution for a logistic regression is:
$$Y_i | \mathbf{x} \sim \text{Bern}(\pi(x_i)) \quad \quad \quad \pi(x_i) = \frac{\exp(\beta_0+\beta_1 x_i)}{1 + \exp(\beta_0+\beta_1 x_i)}.$$
The function $\pi$ is a logistic function of an affine transformation of the argument value $x_i$.

The logistic regression model can be represented using various (equivalent) model forms that yield the above response distribution.  One of these model formulations uses a pseudo-error term with a standard logistic distribution.  Taking $\varepsilon_i \sim \text{Logistic}(0, 1)$ we have:
$$\begin{equation} \begin{aligned}
\mathbb{P}(\beta_0+\beta_1 x_i + \varepsilon_i > 0) = 1- F_{\varepsilon_i}(0)
&= 1 - \frac{1}{1 + \exp(\beta_0+\beta_1 x_i)} \\[6pt]
&= \frac{\exp(\beta_0+\beta_1 x_i)}{1 + \exp(\beta_0+\beta_1 x_i)} \\[8pt]
&= \pi(x_i). \\[6pt]
\end{aligned} \end{equation}$$
Since this is the probability of a positive response outcome in the above distribution, we can formulate the logistic regression model in a way that is similar to a standard linear regression model, but with a pseudo-error term that is only used to classify the response into two categories:
$$Y_i = \mathbb{I}(\beta_0+\beta_1 x_i + \varepsilon_i > 0) \quad \quad \quad \varepsilon_1, ..., \varepsilon_n | \mathbf{x} \sim \text{IID Logistic}(0, 1).$$


$n$ piles, $m$ objects. Choose two piles and remove n objects in total from the two piles. Iterate. For which (m,n) is it possible to empty all piles.

Question: Let $m < n$ be positive integers. Start with $n$ piles, each of $m$ objects. Repeatedly carry out the following operation: choose two piles and remove $n$ objects in total from the two piles. For which $(m,n)$ is it possible to empty all the piles?
I think it is the case that for $k$, natural number, $(k,2k), (ak, ak+a)$ works.
Observation: $m\ge n/2$.
Non-trivial solvable case: $(m,n)=(9,12)$
The first solution is trivial. I proved the second one by induction.

Are there any other solutions and is the second solution correct?
Comment: So you are obligated to take at least $1$ object from each of the two piles, right?
Comment: Yes. Since n>m.
Comment: Not following the rules.  Say there are $10$ piles, each with $2$ objects.  That corresponds to $(m,n)=(2,10)$, right?  But how could I hope to remove $10$ objects from two piles?  And if I can just empty those two piles, and then move on to the others...well, where's the obstruction to emptying all the piles?  Or did you mean for use to assume that $2m≥n$?
Comment: Yes, correct. That's the point. The question is you need to find for which m,n it works (i.e. end up with none left). Something you should note is that m=>n/2
Comment: I suggest adding this to your post...it's not something one would guess easily.  Also:  why not add an explicit example of a non-trivial solvable case?
Comment: Done. If you read the problem, and look at a few cases, it is something that one could easily see within 2mn. I also added the example, which can be derived from my formulae
Comment: Can you elaborate on why $(9, 12) $ is non-trivial?
Comment: Note that $(b, 2b) $ is  a subcase of $(ak, ak+a)$, like with $ a = b, k = 1$.
Answer: The answer is the set of pairs $(m,n)$ such that $n>m$ and $n-m\mid m$. First, let $m=(n-m)k$, where k is a positive integer. It can be rewritten as $m(k+1)=nk$. Since $k$ and $k+1$ are always coprime, $k\mid m$ and $k+1 \mid n$. If we denote gcd$(m,n)$ by $a$, we get the answer in your form $(ak, ak+a)$.
Now let us prove that all such pairs work. We have $k+1 \mid n$, so we divide all the piles in groups of $k+1$. Each group can be processed as follows: we take the first pile ($m$ objects) and $1/k$-th part of the last pile in the group (remember that $k\mid m$), then the second pile and again the part of the last pile, and so on.
Finally, let us prove that $n-m\mid m$ is a necessary condition. Assume that at some step we took $k$ objects from a pile, where $n-m \not\mid k$. What did we take from the second pile? $n-k$ objects. Since there are $m$ objects in any pile, the fate of the other $m-(n-k)=k-(n-m)$ is still unknown. Note that $k-(n-m) \not\mid k$. All these objects were taken at some point, perhaps in several steps. But there was such a step when we took the number of objects from these $k-(n-m)$ which is not divisible by $n-m$. We can repeat this reasoning and every time the number of objects will get smaller but would never be divisible by $n-m$. So it can't get to $0$ which it should.
Therefore, number of the objects we take from a pile is divisible by $n-m$, and so is the number of the objects in the whole pile. We are done.


Como receber meu array na pagina JSP

Question: public void Pesquisar(){
    try {
        Class.forName("com.mysql.jdbc.Driver");
    try {
    Connection conexao = DriverManager.getConnection("jdbc:mysql://localhost/CadastroProdutos", "root", "maquinarafa");
    Statement comando = conexao.createStatement();
    String comandoSQL = "select id_produto, nome, descricao, fornecedor,quantidade,tipo, link  from cadastro_produtos";
    ResultSet rsClientes= comando.executeQuery(comandoSQL);
    while(rsClientes.next()){
        System.out.println(rsClientes.getString("id_produto")+";"
                                +rsClientes.getString("nome")+";"
                                +rsClientes.getString("descricao")+";"
                                +rsClientes.getString("fornecedor")+";"
                                +rsClientes.getString("quantidade")+";"
                                +rsClientes.getString("tipo")+";"
                                +rsClientes.getString("link"));
        String idd = rsClientes.getString("id_produto");
        String name = rsClientes.getString("nome");
         String desc =rsClientes.getString("descricao");
         String forn = rsClientes.getString ("fornecedor");
         String qtde = rsClientes.getString ("quantidade");
         String tip=rsClientes.getString ("tipo");
         String caminhoimag=rsClientes.getString("link");
         //adicionando para o objeto
         Produto p2 = new Produto();
         p2.setId(idd);
         p2.setNome(name);
         p2.setDescricao(desc);
         p2.setFornecedor(forn);
         p2.setQuantidade(qtde);
         p2.setTipo(tip);
         p2.setLink(caminhoimag);
         p2.arrayproduto.add(p2);
        }

/////eu tenho um metodo que pesquisa e retorna meud dados do mysql para o arrayproduto , porem quero acessar este array em uma pagina JSP >>>>>
JSP PAGE
<%@page import="Classes.Produto"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.Iterator"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Relatório de Produtos </title>

 Relatório de Produtos

<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<%
Produto p = new Produto();
ArrayList<Produto> array =  ???? nao sei como receber este array na jsp
%>

Answer: Boa noite Rafael,
Para ter acesso a esta collection no JSP vai depender de como você está fazendo a chamada pro JSP.
Caso esteja usando o método request.getRequestDispachter().forward(req,resp) então você consegue ter acesso a lista adicionando-a em um request attribute através do método req.setAttribute("key", "value").
Caso esteja usando um resp.sendRedirect() dai fica um pouco mais chatinho. As opções não são tão viáveis assim como o método acima. O motivo disso é que com o método resp.sendRedirect() passa a responsabilidade da requisição para o cliente, e a Servlet deixa de renderizar essa page.
Uma das alternativas é usar uma sessão através do método req.getSession().setAttribute("key", "value") (Só não se esqueça que a sessão permanece ativa durante várias requisições. Então você teria que limpar quando necessário pra evitar confusão.
Suponho que você esteja usando o primeiro método (mais ideal).
No seu exemplo, ficaria algo assim..
request.setAttribute("lista_produtos", p2.arrayproduto);.
E no seu JSP, você teria acesso assim:
<% List array = (List) request.getAttribute("lista_produtos"); %>
Espero que tenha ajudado.
Abraços.

Como receber meu array na pagina JSP


R help options - setting help_type="text" for good

Question: How to set for good parameter help_type="text" in R ? Have I to type command options(help_type="text") every time I start R session, or could it be setted as constant ?
Answer: You can put that option choice in a <code>.Rprofile</code> file in the directory in which you start R. I use that method to load frequently used functions and a default set of packages.
I suppose I should mention that files beginning with a period (so-called dot-files) are sometimes hidden by the OS. (I know this to be true on Macs and Windows boxes.) On a Mac you can change the behavior of the Finder.app to display these files. That means you can use your OS GUI to edit them. (Not all of us are Emacs-capable.)
Comment: Yes, see `help(Startup)` for the options to customize your R session.


Automate create credentials for devices to connect AWS IOT Core

Question: I got some problems when try to use AWS IOT Core.
Suppose that I have thousands iot devices and 1 mobile app, 1 backend server.
My thought is I'll provide a common key for devices which has connect policy only, then when their fist connection with aws iot, it wil automate register new credentials with more roles like publish/subscribe.
Is that right?
I've follow some guide on aws documents like JITR but still not work.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer:
My thought is I'll provide a common key for devices which has connect policy only, then when their fist connection with aws iot, it wil automate register new credentials with more roles like publish/subscribe.

It must to register with AWS IoT via certificate signed by your own certificate(CA).

AWS IoT allows the use of a single certificate for an unlimited number of devices to simplify testing but this pattern is strongly discouraged for production use.


call_user_func_array() usage mysqli

Question: I'm trying to simply update a table with dynamic variables and I am stuck, I have read and searched how to do dynamic binding and have found out that I need to use call_user_func_array() but I tried to use it as below and it still doesn't work, can someone show me how to use it?
$a = array('ssi');
$b = array($_POST['h'], $_POST['m'],  2);
$params = array_merge($a, $b);

 $stmt = $db->prepare("UPDATE `test` set field_1 = ?, field_2 = ? where id = ?");
 call_user_func_array(array(&$stmt, 'bind_param'), $params);
 $stmt->execute();

I am getting the below error
Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given

can someone help me out? I have looked at other similar questions and still stuck.
Comment: `var_dump($stmt);` PS: Why did you put `&` in front of `$stmt`?
Comment: Are you mixing up the arguments in call_user_func_array()? http://php.net/manual/en/function.call-user-func-array.php says that the first argument should be the function name (bind_param) to be called, and then an array of (references to) function params as second argument.
Comment: What other similar questions did you look at? Why did you stick with `mysqli` then, if PDO avoids that workaround?
Comment: @zerkms, I did the var_dump and it gave me `bool(false)` and I was able to fix it since I had the table name wrong. now I am getting ` Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given` I just copied it from other answers.
Comment: @Mario http://stackoverflow.com/questions/793471/use-one-bind-param-with-variable-number-of-input-vars, http://stackoverflow.com/questions/5100046/how-to-bind-mysqli-bind-param-arguments-dynamically-in-php
Comment: Sorry, I'm wrong (above), an array as first argument is perfectly fine when the function is a class method.
Answer: What is wrong with this?
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

$params = array($_POST['h'], $_POST['m'],  2);

$stmt = $db->prepare("UPDATE `test` set field_1 = ?, field_2 = ? where id = ?");

$stmt->execute($data);

Alternatively, if you insist on mysqli:
$db = new mysqli($host, $user, $pass, $dbname);

$stmt = $db->prepare("UPDATE `test` set field_1 = ?, field_2 = ? where id = ?");

$stmt->bind_param("ssi", $_POST['h'], $_POST['m'],  2);

$stmt->execute();

Comment: Thanks, fixed that quote. PDO is a much better database interface; I assume the OP is learning this stuff so would rather point him or her in the direction of something better than what they're trying to do. I wish PDO had been around back when I started out!
Comment: Thanks, while the alternative method was pointless since I am trying to avoid binding like that, the PDO version was much easier and it worked.
Comment: Yup, PDO is much superior, no worries about counting how many s and i you have in your statements, just pass your array and go!

call_user_func_array() usage mysqli


Writing text on LaTeX \part page

Question: I was wondering if it is possible to write an introductory text on the page generated by \part{...} in LaTeX?
I have tried to insert text on it, but it will just generate a blank page before the text.
Regards,
Kenneth
Answer: You may define own macro \mypart.
For example
\def\mypart#1#2{%
  \par\break % Page break
  \vskip .3\vsize % Vertical shift
  \refstepcounter{part}% Next part
  {\centering\Large Part \thepart.\par}%
  \vskip .1\vsize % Vertical shift
  % Some text
  #2
  \vfill\break % Fill the end of page and page break
}

\part{Main}{Something about main...}

Comment: Thank you Alexey! I ended up with the following:

\def\mypart#1#2{%
  \par\newpage\clearpage % Page break
  \vspace*{5cm} % Vertical shift
  \refstepcounter{part}% Next part
  {\centering \textbf{\Huge Part \thepart}\par}%
  \vspace{1cm}% Vertical shift
  {\centering \textbf{\Huge #1}\par}%
  \vspace{2cm}% Vertical shift
  % Some text
  #2
  \vfill\pagebreak % Fill the end of page and page break
}
Comment: I tried this way, but then the name of the part does not appear in the index page.
Answer: If you are using the memoir class then a simpler (but less general) method is to just redefine the \afterpartskip command.
I wrote:
\renewcommand{\afterpartskip}{\vfil}

in my preamble.
This works because the pagebreak is generated from
\newcommand{\afterpartskip}{\vfil\newpage}

in memoir.cls.  (It is called from the \partpageend command).
This method simply removes the \newpage command, which might be all you want to do.
Comment: This is exactly what I needed. I just wanted to add a figure below the part title. Then after inserting the graphics I can put in a \vfil and \newpage. Not a big deal, and much simpler than the other solutions.
Comment: I found this, in combination with adding `\nopartblankpage` let me add content to the part page.
Answer: This solution works without any macro and with a correct entry in the Table of Content
\part[Title for TOC]{Title on part-page
                             \\ \\
                  \begin{center}
                     \begin{minipage}[l]{11cm}
                       **Additional text on part page**
                     \end{minipage}
                  \end{center}
                 }

Comment: I like this solution. The only thing that bothers me is the formatting of the additional text. I added `\textnormal{\normalsize **text here**}` to get the fontsize back to normal, but the spacing between the lines stays large.
Comment: @JazZeus have you found any solution for this?
Comment: @SimonH can you elaborate on the question what exactly you do? Why do you center the minipage? Isn't centering default for parts? Why do you have two line breaks? Would \vspace do the job as well? The case is that in my case this solution works but as soon as I touch something, the whole text moves around on the page. I use the scrbook class.
Answer: Another solution for the srcbook class can be found at https://tex.stackexchange.com/questions/273340/old-code-to-define-part-in-scrbook-does-not-work-with-tex-live-2014-and-i-need which looks like this (I am citing):
\documentclass[10pt, german, twoside, openright, headings=small, bibliography=totoc, footinclude=false, mpinclude=false, headinclude, captions=tableheading, numbers=noenddot, cleardoublepage=empty, index=totoc
%, draft
]{scrbook}

\usepackage[ngerman]{babel}

\usepackage[T1]{fontenc}
\usepackage[latin 1]{inputenc}

\setkomafont{partnumber}{\Huge}
\renewcommand\raggedpart{\raggedleft}

\begin{document}
\setpartpreamble{%
  \vspace*{20pt}%
  Im Teil A dieses Buches soll zunächst anhand konkreter Beispiele aus Natur und Technik gezeigt werden, ...
}
\part{Einführung in wichtige Aspekte und Phänomene der Strömungsmechanik}

\end{document}

Writing text on LaTeX \part page


Operadores de Incremento e Decremento

Question: Por que ele não somou o valor da variável 1 , com mais 1 na primeira printf.
<code>int numero = 1;
printf("Conteudo armazenado na variavel: %d\n", numero++); /*(por que aqui da resultado 1? não estou pedindo para ele somar?)*/
printf("Conteudo armazenado na variavel: %d\n", numero++);
</code>
Answer: Sugiro que procures a diferença entre ++x e x++ link
Ex:
x=1;
Com o x++ ele imprime o valor 1 e so no 2º print é que imprime 2
Caso seja ++x ele vai imprimir o 2, porque vai somar primeiro
Comment: , muito obrigado !!

Operadores de Incremento e Decremento


Text pasted in CKEditor isn't clean

Question: On a Drupal 8 installation, with CKEditor enabled for Full HTML format, when I paste text from Word with cmd+V, the source code includes format that makes the code dirty.
Example:

Lorem ipsum dolor.

How can I force it to clean the code from Word?
Answer: For reference, there was a backwards-compatibility break in CKEditor v4.6 - it removed some of its own paste-from-Word button's cleaning. See this discussion on the Drupal side: https://www.drupal.org/project/drupal/issues/2871539
Note comment #6 there offers another workaround - responding to the
afterPasteFromWord CKEditor event in some custom Javascript and filtering exactly as desired.
Answer: This answer is only for CKEditor in Drupal.
I can recommend two modules to clean up pasted text (not only from Word) into the CKEditor:
CKEditor Paste Filter.
This module works out of the box without further settings.
Paste Format (filter, clean-up pasted text).
This module has no stable release (Feb 2022) for Drupal 8/9, but the linked port to Drupal 8/9 works quite well. Nevertheless, I prefer it to the first module, because it works by using a "normal" textformat like "Plain Text". Because of that you have the opportunity to further tweek and restrict the pasted text.
I am using a custom textformat "Pasteformat" with "Convert line breaks into HTML" and "Limit allowed HTML tags and correct faulty HTML" enabled for the following tags:

For "Paste Format" i also recommend the installation of the following modules and enabling them in your textformat for pasting text:
No Non-breaking Space Filter to remove   (has to be the first filter in the textformat).
Filter Empty Tags to remove empty tags and lines (last filter in the textformat).
After all i can safely give the website to customers which want to paste text from word into the editor – without the risk of breaking design and typography.  ;-)
Answer: Two options:

there is a special "Paste from Word"-button in CKeditor, add it to your toolbar
limit allowed HTML tags, it will strip unwanted tags attributes when saving the node (by default spans are allowed, but style attributes will be removed by default)

Both can be done in Configuration > Content authoring > Text formats and editors
Comment: "limit allowed HTML tags" worked for me, thanks @Hudri. "Paste from Word"-button dowsn't work in some browsers, for example in Chrome for Mac shows the error: "Your browser doesn't allow you to paste this way. Press ⌘+V to paste."
Comment: Yes, I do get the same message when pasting in chrome for windows, but it did work in IE

Text pasted in CKEditor isn't clean


Nullpointer Exception unknown resource springmicriservice

Question:
cnv any one help me I dont knoe where make mistake,when i run my
application in chrome in browser when type
http://localhost:8100/currency-converter-feign/from/USD/to/INR/quantity/1000
i got this type of erro
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
Fri Jul 17 21:38:29 IST 2020 There was an unexpected error
(type=Internal Server Error, status=500). No message available
java.lang.NullPointerException at
java.math.BigDecimal.multiply(Unknown Source) at
com.main.conteoller.CurrencyconversionController.convertCurencyFfeign(CurrencyconversionController.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:215)
at
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:142)
at
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at
currencyconvertercontroller.java

package com.main.conteoller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.main.Bean.ConversionBean;
import com.main.serviceproxy.CurrencyexchangeserviceProxy;

@RestController
public class CurrencyconversionController {

    @Autowired
    private CurrencyexchangeserviceProxy proxy;

    @GetMapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}")
    public ConversionBean convertCurency(@PathVariable String from,
            @PathVariable String to,
            @PathVariable BigDecimal quantity) {

        Map<String, String>uriVariables= new HashMap<>();
        uriVariables.put("from", from);
        uriVariables.put("to", to);
        ResponseEntity<ConversionBean>resp = new RestTemplate()
                .getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}",
                ConversionBean.class,
                uriVariables);
               ConversionBean cbresp=resp.getBody();
        return new ConversionBean(cbresp.getId(),from,to,cbresp.getConvermultiple(),
                        quantity,quantity.multiply(cbresp.getConvermultiple()),cbresp.getPort());

    }
    @GetMapping("/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}")
    public ConversionBean convertCurencyFfeign(@PathVariable String from,
            @PathVariable String to,
            @PathVariable BigDecimal quantity) {

               ConversionBean cbresp=proxy.retrivefromexchange(from, to);
        return new ConversionBean(cbresp.getId(),from,to,cbresp.getConvermultiple(),
                        quantity,quantity.multiply(cbresp.getConvermultiple()),cbresp.getPort());

    }
}

currencybean.java

package com.main.Bean;

import java.math.BigDecimal;

public class ConversionBean {
    private int id;
    private String from;
    private String to;
    private BigDecimal convermultiple;
    private BigDecimal quantity;
    private BigDecimal totalCalamount;
    private int port;

    public ConversionBean() {}

    public ConversionBean(int id, String from, String to, BigDecimal convermultiple, BigDecimal quantity,
            BigDecimal totalCalamount, int port) {
        super();
        this.id = id;
        this.from = from;
        this.to = to;
        this.convermultiple = convermultiple;
        this.quantity = quantity;
        this.totalCalamount = totalCalamount;
        this.port = port;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFrom() {
        return from;
    }
    public void setFrom(String from) {
        this.from = from;
    }
    public String getTo() {
        return to;
    }
    public void setTo(String to) {
        this.to = to;
    }
    public BigDecimal getConvermultiple() {
        return convermultiple;
    }
    public void setConvermultiple(BigDecimal convermultiple) {
        this.convermultiple = convermultiple;
    }
    public BigDecimal getQuantity() {
        return quantity;
    }
    public void setQuantity(BigDecimal quantity) {
        this.quantity = quantity;
    }
    public BigDecimal getTotalCalamount() {
        return totalCalamount;
    }
    public void setTotalCalamount(BigDecimal totalCalamount) {
        this.totalCalamount = totalCalamount;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }

}

currencyexchangeproxy.java

package com.main.serviceproxy;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.main.Bean.ConversionBean;

@FeignClient(name="currency-exchange",url="localhost:8000")

public interface CurrencyexchangeserviceProxy {
    @GetMapping("/currency-exchange/from/{from}/to/{to}")
    public ConversionBean retrivefromexchange(@PathVariable ("from") String from,
            @PathVariable ("to") String to);

}

Comment: Do you have the @EnableFeignClients somewhere in your project? If not please put it to your application class and try again.
Comment: @EnableFeignClients it is declared in my main method below my SpringBootApplication
Answer:
It is occurs due to mismatch of comumn name in your  db table and in
your entity class. Because I use micriservices,I call some exchange
rates from another project by provideing its url in my repository, in
that project i privide same name in my entity class and in my db table
,but i declared diffrent name in my exchange service project. there i
declare conversationmultople and here declare convermultiple
.make sure both name same in db and your bean class
Answer:
@EnableFeignClient service in your springboot main method
for example

package com.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients("com.main.serviceproxy")
public class CurrencyConversionServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(CurrencyConversionServiceApplication.class, args);
    }

}


Input ao clicar em Adicionar

Question: Quero que ao clicar em adicionar seja acrescentado um novo input, com nome certinho para que eu possa pegar as informações e enviar através do formulário.
Segue o código.

        Pedidos

<form method="POST" action="recebe.php?valida=TRUE">
   Cód. Produto: <input type="text" name="codProduto"/>
   Quantidade: <input type="text" name="qtdProduto"/>
   <input type="button" name="adicionar" value="adicionar"/>
   <input type="submit" value="Enviar"/>
</form>

Página que pega as informações do formulário.

        Recebe

<?php

if($_REQUEST["valida"] = TRUE && isset($_REQUEST["valida"])) {
    echo "Código do Produto: " . $_POST["codProduto"] . "
";
    echo "Quantidade do Produto: " . $_POST["qtdProduto"];
  } else {

  }
?>

Comment: Adicionar que input? Em `$_REQUEST["valida"] = TRUE`, um `=` é atribuição, acredito que o que quer é comparação, no caso, troque por `==`
Comment: Verdade, vou fazer essa alteração. Amigo, quero que ao clicar no botão ADICIONAR apareça outro input de CódProduto e outro input QtdProduto
Comment: Bem-vindo Fransuwel, se alguma resposta lhe serviu não deixe de marcá-la como aceita. Veja como nessa imagem https://i.stack.imgur.com/evLUR.png e porque nesse post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Comment: Fiz uma validação correta, veja resposta editada `Para retornar somente os valores dos inputs preenchidos aos pares`
Answer:

$(document).ready(function() {
   var maximo = 5;   //maximo de 5 campos
   var i = 1;
   $('#add_div').click (function(e) {
     e.preventDefault();  //previne novos cliques
     if (i < maximo) {
       $('#idDiv').append('
\
          Cód. Produto: <input type="text" name="codProduto[]"/> Quantidade: <input type="text" name="qtdProduto[]"/>\
          Remover\

');
           i++;
     }
  });

    // Remove o div anterior
    $('#idDiv').on("click",".remove",function(e) {
      e.preventDefault();
      $(this).parent('div').remove();
      i--;
    });
});

<form method="POST" action="recebe.php?valida=TRUE">
<input type="button" id="add_div" value="adicionar"> <input type="submit" value="Enviar"/>

    Cód. Produto: <input type="text" name="codProduto[]"/>
    Quantidade: <input type="text" name="qtdProduto[]"/>

</form>

ADICIONAR
Ao botão (definido no HTML) com o id="add_div", adicionamos a função "click" para que, ao clicar, seja executada a função definida.
Primeiro, não permite mais clicks (um de cada vez) e verifica se já temos o máximo de divs possíveis – definido no inicio – var maximo = 5;
Se não acontecer, vamos usar a função append do jquery para adicionar mais uma div (uma div com 2 inputs) a div inicial, com o id="idDiv". Posteriormente Incrementamos o i.
REMOVER
Usamos a função on do jquery, para adicionar eventos de click as divs adicionadas.
Porque temos que usar esta função? Porque, ao carregar o documento, o browser analisa o DOM, e qualquer código de javascript (ou jquery) que tenhamos é automaticamente inicalizado e os eventos "atribuídos". No entanto, estas DIVS são adicionados dinamicamente, não existem quando o documento é carregado. Assim, temos que usar esta função para adicionar o evento "click" a correspondente DIV.
Depois, usamos a função .parent do jquery para remover o div correspondente.
Com este código, o DIV que vamos remover é aquele onde pressionamos REMOVER e não o ultimo inserido.
Para coletar

Note que foi adicionado [] colchetes no atributo namedos inputs. Quando você coloca um "name" com [] colchetes ele é enviado na forma de array para o receptor.

  $codProduto = $_POST['codProduto'];
  $qtdProduto = $_POST['qtdProduto'];

  $result = count($codProduto);

    for ($i = 0; $i < ($result) ; $i++) {
      echo "Código do Produto: " . $codProduto[$i];
      echo " - Quantidade do Produto: " . $qtdProduto[$i] . "
";
    }

Para retornar somente os valores dos inputs preenchidos aos pares:
if ($_POST['submit']=="Enviar"){

    $codProduto = array_filter($_POST['codProduto']);
    if (empty($codProduto)){
        $erro = "Código do Produto é requerido
";
    }

    $qtdProduto = array_filter($_POST['qtdProduto']);
    if (empty($qtdProduto)){
       $erro .= "Quantidade do Produto é requerido
";
    }

    if ($erro == ""){

       $result = count($codProduto);

       for ($i = 0; $i < ($result) ; $i++) {

          if ($codProduto[$i]!="" && $qtdProduto[$i]!=""){
            echo "Código do Produto: " . $codProduto[$i];
            echo " - Quantidade do Produto: " . $qtdProduto[$i] . "
";
          }

       }

    } else {
      echo $erro;
    }

}

Comment: Funcionou, agora como faço para coletar essas informações, de cada input?
Comment: @Fransuwel, veja na resposta como coletar, acabei de postar. Faça o teste e me diga se OK
Comment: Não pega os valores do primeiro input
Comment: Perdão!!!Pega sim, estou testando
Comment: Só tem mais esse problema, realmente ele não pega o valor quando se digita apenas o primeiro input
Comment: Não coleta o valor do primeiro input porque o javascript roda quando se clica no adicionar, quando clicar em enviar direto não funciona
Comment: @Fransuwel, repare que  na condicional `if` do PHP só entra se os 2 campos forem iniciados, mas você pode mudar a sua vontade
Comment: Vou testar, guenta ai
Comment: Estou no aguardo,
Comment: @Fransuwel eu copiei e colei um `for` de outro script PHP.  Editei a resposta com ele correto `for ($i = 0; $i < ($result) ; $i++) {`
Comment: Perfeito!Muito obrigado amigo, você é fera.

Input ao clicar em Adicionar


View exposed filter with month and remove year

Question: I have an issue that needs the help of everyone. I created the page in view to filter the node. I created a filter Date created in "view exposed filter" for filter by  Date created.
I configured for the Filter granularity is check month,  that filter will display 2 dropbox to me to choose, i.e. month and year dropbox. But I want to display only months option and defaults year is the current year. Do not know if anyone can help me handle the matter.
Thank you very much
Answer: Using CSS and jQuery you can achieve your requirement.
Step 1: Using jQuery, on change() event of month select list assign current year to year select list.
<code>$(".date-month").change(function(){
    //write code to set current year to year select list.
});
</code>
Step 2: Now using CSS, hide year select list.
<code>.date-year {
    display: none;
}
</code>

Note: You can also achieve the same functionality using Drupal custom hooks.
Comment: How i can use form_views_exposed_form_alter?
Comment: Sorry, I have not tried form_views_exposed_form_alter hook.
Comment: Hi. You can look Month and Year dropbox. It have label is '-Month' and '-Year'. I want change it to '-Month-'. How i can change it?
Comment: To change the label, you can also do it using jQuery. Please always make sure to ask new question, when you have any new thing to discuss.
Comment: Oh. When i set value for year by jquery when i serch not select month it will display validate required month.
Comment: On page load, let the value of Year filter be -year. Set year value to current year ONLY on change event of month select list i.e. when somebody select month.


equivalence between reduced and unreduced homology theory

Question: I'm trying to prove that a reduced homology theory can be define from an unreduced one, but the problem is to define a border map for the reduced homology using the unreduced homology groups.
Comment: Huh? What's a "border map" -- you mean boundary map in homology? $\tilde{H}_n=H_n$ for $n>0$ and $\tilde{H}_0\oplus\mathbb{Z}=H_0$.
Answer: You might know, Hatcher uses the maps
$\overline H_n(X)=\ker(H_n(X)\rightarrow H_n(point))$
$H_n(X)=\overline H_n(X\sqcup point)$
It's left as an exercise to check that these two maps are inverses of each other as transformation of the unreduced and the reduced homology theories.
Comment: Hello Aneesh! Hatcher gives maps but I don't know if theese really define homology theories, I want to prove this before the equivalence..


Is stepwise elimination of insignifcant variables invalid if applied to experimental data?

Question: Setting: Experimental data and control-variables
I want to evalute the (average) treatment effect in a randomized controlled trial. Individuals $i$ in one group received a treatment ($D_i=1$) and in another group a placebo ($D_i=0$).
In order to reduce estimation uncertainty I control for pre-treatment variables which predict the outcome (e.g. survival is prediced by age, this holds regardless of treatment). The regression equation I estimate is:
$$Y_i =  \alpha + \beta D_i + \gamma X_i,$$where $X_i$ is a vector of covariates.
Selecting $X_i$
There are several aspects to be considered when deciding on $X_i$.
By design (randomization) the covariates will be uncorrelated (in expectation) with treatment status. Their inclusion may increases the precision of the $\beta$-estimation if they "suck-up" noise in the outcome variable, but they might also increase estimation uncertainty by costing degrees of freedom.
The choice of covariates is hence non-trivial and of course also leaves room for p-hacking.
My question: Do stepwise procedures (such as the stepwise elimination of variables with insignificant coefficients) invalidate inference regarding $\beta$?
My understanding is that such proceedures generally lead to overfitting. Yet, if I only apply it to variables within the vector $X_i$, and the only inference I care about is regarding $\beta$ I fail to see how this would become a problem. What would be an example for a data generating process illustrating this?
Edit:
Schematic example for a stepwise proceedure.

Let $X_i$ contain all base-line variables, transformations of those (e.g. logs squares), and their interactions.
Estimate $Y_i =  \alpha + \beta D_i + \gamma X_i$, using OLS
Drop from $X_i$ all entries variables for which the coefficient estimate in 2 had a p-value below, say, 5%
If any variables were dropped in 3., goto 2, if not continue to 5
Report the estimate for $\beta$ obtained in the last iteration of 2.

My intuition is that this would yield unbiased estimates of $\beta$, but biased estimates of $SE[\hat\beta]$. But I might be wrong and happy to be proven wrong.
If estimates for $\beta$ would be biased I would be interested to hear why/see an example for such a D.G.P.
EDIT2:
I will select the answer to this question, which provides at least a scematic example of a d.g.p. with which I would get undersized test restults for the ATE, under random treatment assignment (even if that only works in small samples).
Comment: I'm struggling to appreciate the question. If there indeed is an effect $\beta\ne 0$, then the null hypothesis is false. Thus the appropriate sense of "bias" must be *conditioned* on the assignment into treatment and control. If that assignment *happens* to be orthogonal to the covariates, you will be fine; but if it is not, then there's nothing special or different about your data than any other dataset and we can apply what is generally known about stepwise procedures.
Comment: Before this question derails into something to specific, I posted the example-coding follow-up question somewhere else: http://www.statalist.org/forums/forum/general-stata-discussion/general/1349822-where-is-the-problem-with-stepwise-proceedures
Comment: Stepwise selection does not improve any aspect of estimation. What made you think it did?
Comment: @Frank, the idea would be that it improves something (regarding the point estimates) if little is known about which controls would improve estimation. Then the alternatives (i) using no controls or (ii) using all controls, could both give less precise point estimates, no? Of course, using the right controls is always best, but they are unknown in most settings.
Answer: Yes, stepwise methods invalidate inference in this setting.  Variables are retained because either (1) they are truly strong or (2) their effects are mis-estimated to be too far from zero.  This creates a selection ("publication") bias.  Even more clearly, variable selection results in a biased-low estimate of $\sigma^2$ which you can almost see from just looking at the formula for $\hat{\sigma}^2$ which is the sum of squared residuals divided by $n - p - 1$ where $p$ is the number of slopes in the model.  With stepwise variable selection, one could say that $p$ is dishonestly low.  Analytsts take $p$ to be the number of retained variables and not the number of candidate variables.  The formula mandates that $p$ be non-stochastic, i.e., pre-specified.
Generally speaking, it is a mistake to think that stepwise variable selection improves estimation of $\beta$.  Using outside knowledge to specify variables to include in the model can improve everything, but using the same dataset to select which parameters to estimate does not.  Some of the information in the data is diverted to vainly try to answer the question "which predictors are important?".  This information is better used in estimation of effects.
Comment: For models that are nonlinear in $\beta$ even orthogonality doesn't protect from bias.
Comment: I don't think it matters but would need you to write out a proposed step-by-step algorithm to know for sure.
Comment: The main idea is that things like odds ratios and hazard ratios are "non-collapsible" meaning that in nonlinear models that do not have an error variance, model misspecification cannot just inflate $\sigma^2$; it spills over into modifying the $\beta$s.
Comment: Destruction of the error variance, which affects every aspect of inference (except for $\beta$ point estimates perhaps) is plenty of reason not to use stepwise methods in this context.
Comment: The algorithm you described is a classic stepwise variable selection approach where a few of the variables are mandated.  It suffers from **all** the problems of stepwise variable selection.
Comment: I believe that reduces the bias (but not for $\sigma^2$) but doesn't make it zero.  This is related to the bad practice in randomized clinical trials of using stepwise testing to decide which variables are included in a model.  You can find meaningless chance imbalances that way, and include variable because they are slightly co-linear with treatment, which hurts the estimate of the randomized treatment effect.
Comment: I could imagine that bootstrapping, doing the whole model building process on each of the bootstrap samples and then basing the estimate & SE (or confidence interval) on the estimates from the bootstrap samples could get you to something that might be valid. Do I know for sure it would have great properties... No. But, it certainly sounds like it would be more promising than what you originally suggested. At least it is not a case of doing model selection and then doing an analysis, as if there had never been any model uncertainty and the selected model had been pre-specified from the start.
Comment: Thank you. What I find confusing still is the following: "Normal" p-hacking using control variables (i.e. picking controls until you find the lowest p-value for your variable of interest) is still somewhat different from the above proceedure, no? Is it correct to say that normal p-hacking will lead to biased (away from zero) ATE-estimates as well as overestimated precision, while such a stepwise proceedure would only overestimate precision (by underestimating $\hat{\sigma^2}$)?
Comment: I don't understand how "it does [not] matter" would be an answer to my question. Can you clarify please? I will edit a proposed step-by-step algorithm into the original question.
Comment: Sure. The only thing that sets me off is that the mandated variable is randomized and hence independent from all the other's. Doesn't  that imply that the endogenous variable selection will not bias it's  estimate?
Comment: I see, the bias probably only vanishes asymptotically.
Comment: can you elaborate on this?
Comment: Thanks, I guess this thread becomes convoluted if I keep asking follow up questions. However, I still find no convincing evidence that in my specific context backward stepwise methods cause issues. I post the question on the Stata-list instead http://www.statalist.org/forums/forum/general-stata-discussion/general/1349822-where-is-the-problem-with-stepwise-proceedures
Comment: If other aspects (improved estimation of $\beta$) improve, I might  consider obtaining my standard errors differently (e.g. bootstrapping). No? And as pointed out in the link above, I fail to find evidence that the particular statistic I'm interested in, in the context I'm interested in, is affected. Happy to be proven wrong.


Preciso clicar no botão duas vezes para obter o valor

Question: Alguem sabe o que fiz de errado, porque eu preciso clicar duas vezes no botão para ele puxar o valor.
package fabiohcnobre.jhotelcolonialdosnobres;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class settingsActivity extends AppCompatActivity {

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef ;

    private String TAG;
    private String statusdareserva;

    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        Button btnbuscar = (Button) findViewById(R.id.button_buscar);
        btnbuscar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView textview1 = (TextView) findViewById(R.id.TextView1);
                EditText editext1 = (EditText) findViewById(R.id.edittext1);
                String status = "Falha";
                status = ProcuraReserva(editext1.getText().toString());
                textview1.setText("1"+ status);
            }
        });
    }

    public String ProcuraReserva(String codigodareserva){
        // Read from the database
        myRef = database.getReference("reserva/"+codigodareserva+"/status");
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String value = dataSnapshot.getValue(String.class);
                statusdareserva = value;
            }

            @Override
            public void onCancelled(DatabaseError error) {
                statusdareserva = "Status com falha";
            }
        });

        return statusdareserva;

    }
}

Answer: O valor de statusdareserva é obtido no método ProcuraReserva() de forma assíncrona.
Repare que teve de criar um ValueEventListener para o receber.
Ou seja, a execução chega à linha return statusdareserva; antes de statusdareserva receber um valor em onDataChange() ou onCancelled().
Entretanto o processo assíncrono(database.getReference()) termina e statusdareserva recebe um valor, que agora está disponível para ser devolvido em return statusdareserva;, quando clicar pela segunda vez.
Você tem de "setar" o TextView dentros do métodos onDataChange() é onCancelled(), pois é aí que ele está disponível quando for lido do banco de dados.
public void ProcuraReserva(String codigodareserva){
    // Read from the database
    myRef = database.getReference("reserva/"+codigodareserva+"/status");
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String value = dataSnapshot.getValue(String.class);
            textview1.setText("1"+ value);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            textview1.setText("Status com falha");
        }
    });
}

Terá de declarar textview1 como um atributo da Activity e iniciá-lo no método onCreate()
Comment: Obrigado pela ajuda Ramaral deu para entender direito como funciona o codigo.
Answer: Neste trecho, o processo esta entrando no metodo, e antes de terminar textview1.settext("1"+ status); ja foi ativado.
status = ProcuraReserva(editext1.getText().toString());
            textview1.setText("1"+ status);

Tenta colocar o textview uma variável global e fazer a mudança dentro do método ProcuraReserva();
teste também se esta entrando nos metodos onDataChange e onCancelled, não tenho certeza.
Comment: Obrigado pela ajuda Icaro.


How to remove session cookie

Question: We are trying to clear the cookie details in browser on pressing 'Logout' button with the following code, but the script doesn't remove the session cookie from the browser. But by clearing the session cookies in IE8 browser using developer tool(Tools > Developer Tools >Cache > Clear Session Cookies), the cookies are cleared.

function logout(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)     {
  var cookiename =  cookies[i].split("=");
  var d = new Date();
  d.setDate(d.getDate() - 4);
  var expires = ";expires="+d;
  var value="";
  document.cookie = cookiename + "=" + value + expires + ";";
  }
}

How to clear the Session cookies from the browser using script?
Comment: possible duplicate of [Clearing all cookies with JavaScript](http://stackoverflow.com/questions/179355/clearing-all-cookies-with-javascript)
Comment: Why do you want to remove the cookie? Call `session.invalidate()` would be enough, the cookie will be deleted on browser exit anyway.
Answer: if it is httpOnly, then you can not delete it, try modify it from server side
Answer: from javascript: Not specifying expiring field, also set value to null, and if it is also hostonly, not specifying domain
Answer: If it is a 'session' variable you want to clear...
unset( $_SESSION['YOUR_SESSION_VARIABLE_NAME'] );

This will completely remove this session variable. The title is misleading. The code he shows is not 'session' cookies, they are regular 'cookies'.

How to remove session cookie


How to eject CD/DVD of KVM-based VM with `qm set`?

Question: I am using Proxmox VE 4.4 and I am puzzled how to eject a CD/DVD drive that is currently configured. Assume that the ID of the guest VM is set as the environment variable vmid.
Currently the configuration qm config $vmid|grep ^ide gives the following:
ide2: iso-storage:iso/SLE-12-SP2-Server-DVD-x86_64-GM-DVD1.iso,media=cdrom,size=3188M

and I'd like to "eject" that drive such that no media is in that drive anymore, but it still exists as CD/DVD drive to the guest (i.e. without removing the drive!).
How can I achieve that from the shell of the Proxmox VE machine (i.e. the host)?
NB: qm cdrom <vmid> eject does not exist in this version of Proxmox VE, but it does appear to have existed in the past.

What I tried:
# qm set $vmid -ide2 media=cdrom
400 Parameter verification failed.
ide2: invalid format - format error
ide2.file: property is missing and it is not optional

qm set <vmid> [OPTIONS]

and
# qm set $vmid -ide2 media=cdrom,file=
400 Parameter verification failed.
ide2: invalid format - missing key in comma-separated list property

qm set <vmid> [OPTIONS]

and
# qm set $vmid -ide2 media=cdrom,file=/dev/null
update VM $vmid: -ide2 media=cdrom,file=/dev/null
volume /dev/null does not exists

Answer: I figured it out on my own.
While almost any value for the <volume> in -ide[n] [file=]<volume> failed (see qm(1)), the undocumented value none did the trick.
   -ide[n] [file=]<volume> [,aio=<native|threads>] [,backup=<1|0>] [,bps=<bps>]
   [,bps_max_length=<seconds>] [,bps_rd=<bps>] [,bps_rd_length=<seconds>] [,bps_wr=<bps>]
   [,bps_wr_length=<seconds>] [,cache=<enum>] [,cyls=<integer>] [,detect_zeroes=<1|0>]
   [,discard=<ignore|on>] [,format=<enum>] [,heads=<integer>] [,iops=<iops>] [,iops_max=<iops>]
   [,iops_max_length=<seconds>] [,iops_rd=<iops>] [,iops_rd_length=<seconds>]
   [,iops_rd_max=<iops>] [,iops_wr=<iops>] [,iops_wr_length=<seconds>] [,iops_wr_max=<iops>]
   [,mbps=<mbps>] [,mbps_max=<mbps>] [,mbps_rd=<mbps>] [,mbps_rd_max=<mbps>] [,mbps_wr=<mbps>]
   [,mbps_wr_max=<mbps>] [,media=<cdrom|disk>] [,model=<model>] [,rerror=<ignore|report|stop>]
   [,secs=<integer>] [,serial=<serial>] [,size=<DiskSize>] [,snapshot=<1|0>]
   [,trans=<none|lba|auto>] [,werror=<enum>]
       Use volume as IDE hard disk or CD-ROM (n is 0 to 3).

I only stumbled across that, because one of the virtual machines in my PVE clustered happened to have that value. So I gave it a try and lo and behold:
qm set $vmid -ide2 media=cdrom,file=none

does the trick.


Custom order processor not being run

Question: I have a custom order processor which currently just logs a debug message, so that I know that the order has been processed by it.
For whatever reason, my order processor is never run, I've checked against the docs, looked at how other commerce modules does it (commerce_promotion and commerce_tax), none of them show that I am doing anything wrong.
custom_commerce.services.yml
services:
  custom_commerce.order_tax_processor:
    class: Drupal\custom_commerce\OrderTaxProcessor
    tads:
      - { name: commerce_order.order_processor, priority: 300 }

OrderTaxProcessor.php class
<?php

namespace Drupal\custom_commerce;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\OrderProcessorInterface;

/**
 * Provides an order processor that adds tax to order if order has adjustments.
 * It does not affect order items.
 */
class OrderTaxProcessor implements OrderProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function process(OrderInterface $order) {
    \Drupal::logger('Custom commerce')->debug('Order processed check');
  }
}

Can anyone see what I am doing wrong? Other order processors seem to be running fine, but mine seems to be ignored/not run.
Running Drupal 8.5.3 and Commerce 2.6.0
Comment: I also have to write a custom  processor but I am getting this error... `'commerce_order.order_refresh' does not implement Drupal\commerce_o
  rder\OrderProcessorInterface.
                                  ` Can you please help me with this
Answer: So I found what caused my problem, a silly typo...
Basically, in my custom_commerce.services.yml I had written tads instead of tags.
I fixed it and it's now running as it should.

Custom order processor not being run


Rspec & FactoryGirl 'Cannot call create unless parent is saved'

Question: I'm sure that my issue is pretty easy to resolve. However, I cannot find how or where to resolve it. Currently I am trying to test the #follow method on my User model. Here is the test that I have:
describe "#follow & #following?" do
 before(:each) do
   @other_user = FactoryGirl.create(:user)
 end

 it "returns false for user following other_user" do
   expect(@user.following?(@other_user)).to eq(false)
 end

 it "returns true for user following other_user" do
   @user.follow(@other_user)
   expect(@user.following?(@other_user)).to eq(true)
 end
end

Here is the #follow method:
def follow(other_user)
 active_relationships.create(followed_id: other_user.id)
end

The error that is being returned is You cannot call create unless the parent is saved. Obviously the parent in question here is @other_user. Now the first test passes as intended because we obviously aren't running a method that calls create like when we run the #follow method. My question is how would I save this @other_user so that I can create an active_relationship.
Here is how @user is being presented:
before { @user = FactoryGirl.build(:user) }
subject { @user }

Also, @user is working with all other tests. When running .persisted? on both @user & @other_user I receive true.
Comment: In the spec file, where and how is `@user` being created?
Comment: Is it really the `@other_user` that is not saved? My guess would be that `@user` is not saved. Call `persisted?` on both of them to test this out. Furthermore you might want to call `errors` on both of them, perhaps the factory does not return valid instances.
Comment: `FactoryGirl.build(:user)` returns an unsave user, i doubt that `@user.persisted?` returns `true`... Please add `@user.save` before `@user.follow(@other_user)` and test if that let's your example pass...
Comment: @spickermann So I tested `@other_user.persisted?` and then changed it to `@user`, or so I thought. I ran `@user.persisted?` again, like spickermann has pointed out, build returns false. Actually creating it will get it to persist, thus saving the parent which is `@user`... You were right all along! Thank you for the help. If there is a better way of going about this, I am all ears.
Answer: You @user is not saved, because Factory.build(:user) returns unsaved records. Just change your specs to save @user before you run that particular example.
I would write the specs like this:
subject(:user) { FactoryGirl.build(:user) }

describe "#follow & #following?" do
  let(:other) { FactoryGirl.create(:user) }

  it "returns false for user following other_user" do
    expect(user.following?(other)).to be_false
  end

  context "when following" do
    before do
      user.save
      user.follow(other)
    end

    it "returns true for user following other_user" do
      expect(user.following?(other)).to be_true
    end
  end
end

Answer: As @spickermann pointed out. The actual parent in question was @user and NOT @other_user. Because I was merely building the user it was returning an unsaved object. Thus not allowing us to create an active_relationship on an object that had yet to be saved. Changing build to create has resolved the issue.
Thanks to Spickermann and Ben Y for their participation


Second derivative of $f(x) = \lg(x) + 5-x$

Question: Can you help me to find the second derivative of
$$f(x) = \lg(x) + 5-x$$
If you can, please, explain it to me.
Thank you.
Comment: $\log$, as in base $10$ or base $e$?
Comment: I hope you know that the derivative of a constant is zero and that of $\log x $ is $1/x $.
Comment: yes, lg @S.C.B.
Comment: lg(x) + 5 -x ; @Rohan
Answer: $$f(x)=\log(x)+5-x$$
so $$f'(x)=\frac{1}{xlog(10)}-1$$
so $$f''(x)=-\frac{1}{log(10)x^{2}}$$ using the quotient rule and that the derivative of a constant is zero
Comment: f(x)=lg(x)+5−x ; lg, not ln
Comment: @VadimMarchenko Log base 10?
Comment: yes, log base 10
Answer: We have $$f (x) = \log_{10} x + 5-x $$ $$\Rightarrow f'(x) = \frac {\mathrm {d}}{\mathrm {d}x}(\frac {\log_e x}{\log_e 10} + 5-x) = \frac {1}{x\log_e 10} + 0 -1 =\frac {1}{x\log_e 10}-1$$ $$\Rightarrow f''(x) = \frac {\mathrm {d}}{\mathrm {d}x}(\frac {1}{x\log_e 10}-1) = \frac {-1}{x^2\log_e 10} + 0 = -\frac {1}{x^2\log_e 10}$$
We have just used the idea expressed in my commemt above. Also $\log_e 10 = \ln 10$, can be taken out of the expression while taking the derivative and does not affect it. Hope it helps.


Ruby pack and unpack. How is this hexadecimal conversion being done? Could use some assistance

Question: I'm having a bit of trouble understanding some code:
Things I understand:
1. The use of the Cipher class and object and the encryption method.
2. The address_string and how it is using | as a delimiter.
3. The update.
My questions:
1. What is cipher.final doing?
2. What is the unpack doing?
  cipher = OpenSSL::Cipher::Cipher.new('AES-256-CFB').encrypt
  iv = cipher.random_iv
  cipher.key = Digest::SHA256.digest(KEY)
  address_string = addresses.map{ |addr| addr.strip }.push(identifier).join('|')
  encrypted_message = cipher.update(address_string) + cipher.final
  binding.pry
  encrypted_message.unpack('H*')[0]

I see this in my terminal:
 encrypted_message
=> ".YI\xCA\xAC\x17\xF2\xBF\x1C^b\x8C[|\xB8YU\x1F\xCBn/\xE5\xA0\x15\x8Aa\ef\xAF>\x7F\x8A"
[2] pry(Mixer)> encrypted_message.unpack('H*')
=> ["2e5949caac17f2bf1c5e628c5b7cb859551fcb6e2fe5a0158a611b66af3e7f8a"]

I understand the basics of binary and hexadecimal... but I'm still having trouble understanding what I see.

What is the encrypted message format? What are the slashes and the \xs. Is it hexadecimal? How do you know? What is the .YI leading part?
How are they converting this to hexa? Can you show an example?
Comment: https://stackoverflow.com/q/48492676/1672429
Answer: encrypted_message is a string starting with the characters .YI. Let's convert those characters to Hex and then binary using the ASCII table:
ASCII  .        |Y        |I
Hex    2    e   |5    9   |4    9
Binary 0010 1110|0101 1001|0100 1001

Notice that the hex is what you see at the beginning of the unpack(H*) result. If you were to call encrypted_message.unpack("B*") (bit string), you would similarly see it start with
001011100101100101001001

The point is

There is no "encrypted message format". encrypted_message is meaningless, structureless binary data.
When you call unpack, you're saying "Take this meaningless binary data, and show it to me with a different representation." In this case, hexadecimal digits. You can similarly see it as binary, like I did above. Or you can look at it as ASCII characters (the default), with \x indicating a byte that doesn't have an ASCII representation. It's all the same binary data just being presented in different human-readable ways.
Comment: This is very clear, but what do you mean by structureless books data? The first character is a period and then a Y... Which are not binary right?
Comment: So the original message is already encoded in ASCII format? But it really is just structureless binary data?
Comment: @Jwan622 Ruby only escapes non-printable characters when printing binary strings, so printable characters within the ASCII range are not distinguishable from ordinary text.
Comment: @Stefan and I guess a correlary to what you're saying is that Ruby auto converts binary to ascii characters?
Comment: @Jwan622 for displaying purposes, yes. Although `"\x68\x65\x6C\x6C\x6F"` might be more consistent, it's much harder to read than `"hello"` ;-)


set different background images to Ext.list in sencha touch

Question: I'm working on Sencha touch application.
I have created list view using Ext.list component of sencha touch.
I have set background images for all list item using CSS
.x-list .x-list-item {
 position: absolute !important;
 left: 0;
 top: 0;
 width: 100%;
 height:20px;
 background: url('../images/list_1.png');
 background-repeat: no-repeat;
 background-size: 97% 98%;
}

Now I want to set different images for different list items. Is this possible?
Comment: try .x-list-item:nth-child() for reference http://www.w3schools.com/cssref/sel_nth-child.asp
Comment: i tried this, bad sadly doesn't work.
Answer: If you are using tpl to generate your list items, simply give your list items a class name, something like:
tpl: '
This is list item 1.
'

then change the bgimage property of the data that you set to the list, something like this should do:
prepareData: function(data, index, record) {
    data.bgimage = "bg-" + index;
}

Then in your CSS/SASS, you can do
.x-list-item.bg-1 {
 background-image: url('../images/list_1.png')
}
.x-list-item.bg-2 {
 background-image: url('../images/list_2.png')
}
…

You could customise this to your needs, but this should get you started.
If you're using list item components (i.e. your list does not have a tpl config but an itemCmp config), just set the cls config on each item to get the same result.
Answer: If targeting them using nth-child is not working you might have to go the more cumbersome route and attach a separate class to each list item in the html and then manipulate their background images in the CSS by changing the background property of each individually


Procedure If exists update else insert em tabela com chave composta SQL Server

Question: Olá.
Estou querendo sincronizar uma tabela com o Linked Server, porém o problema é que a tabela tem chave primária composta, e não sei como fazer a verificação para buscar o registro.
Alguém pode me ajudar por favor?!
Obrigada!
Answer: Desta forma que vou lhe mostrar garante a integridade dos dados com o uso do transaction, veja se isso lhe ajuda:
begin tran
if exists (select * from Sua_tabela with (updlock,serializable) where key1 = @key1 and key2 = @key2)
begin
   update Sua_tabela set ...
   where key1 = @key1 and key2 = @key2
end
else
begin
insert Sua_tabela (key1, key2 ...)
values (@key1, @key2, ...)
end
commit tran

ou
begin tran
   update Sua_tabela with (serializable) set ...
   where key = @key and key2 = @key2

   if @@rowcount = 0
   begin
      insert Sua_tabela (key1, key2, ...) values (@key1, @key2, ...)
   end
commit tran


How to audit security on Remote Employees' PCs?

Question: We have several remote developers who are working on our code and have access to our FTP server. Recently someone copied an infected file to the FTP server and virus spread throughout the whole FTP server. We can't install antivirus on the FTP server.
We can't force people to install an Internet Security Tool (e.g. Norton, Gdata, Kaspersky) on every machine because most of our remote employees have their own computers and own software. So I am looking for some audit tool - I want to make employees test their own computer once in a while.
I know there is "Trojan Remover" which scans the computer. Is it enough or maybe you can recommend better solution?
Comment: Why can't you install AV software on your FTP server?
Comment: Sometimes you need to run the EmployeeRemover.
Comment: i can't because i don't have my own ftp server - we are using ftp account in some hosting company
Comment: Can you not ask them to install one or host your own FTP, it's very easy.
Comment: that really would be the best solution.
Comment: setup your on ftp server.
Answer: Solving this the way you describe is more a management/policy issue than an IT issue. As the problematic machines are outside of your sphere of control there's not an easy tech solution for that.
A few suggestions though of things you can do:

Have any person who has access to your VPN/remote servers/etc sign something stating they have taken adequate precautions and run anti virus etc.
Run a gateway anti virus on your network to catch these things as they come in.
Find a way to install anti virus on the FTP server! I know you say you can't, but maybe that in itself is an issue. There are a myriad of anti virus programs available for Windows, and there's also several for Linux. If you are running a Linux FTP server, try ClamAV. It's available in most distro repos.
Answer: Well, no way to do that.
There are 2 ways that make sense:

Either force users to audit their machines. Windows has a mechanism for that on their VPN system which can make a check whether the machine is "known patch level".
Or keep them out of your network and make them work on a terminal server / virtual machine, which means you control the system.

Between the two there is nothing left. Not forcing them to install proper software and them not running on a machine controlled by you means that you have a high security hole that you cannot close.
Answer: You should find a way to get an anti-virus running, this is your best option. You might get threats in from other places than your people uploading files to it.
It's like getting a venereal disease and saying "Well I got infected, but a condom just isn't an option"
If you can't install an AV on your own server, that means something is wrong with your policy or setup.
Comment: I don't know that I'd've picked that example, but it's extremely... errrm.... graphic.  It definitely focusses the mind on the underlying problem!  Pajak, you do seem to be saying that you can't secure the source platforms, and that you can't secure the destination platform, then asking how you can secure the system as a whole, and I don't think that question can be answered.
Answer: hmmm ...
build a virtual machine with all your dev tools and distribute it to all your outside developers. Then have them only connect and work through the vm. That way you can have control over the environment without forcing anything other than a vmplayer on the user.


Preventing a fixed header from hiding text with CSS

Question: Given
, with the following CSS:
#pageheader { position: fixed; top: 0px; width: 100%; height: 35px; }
body { margin-top: 35px; }

I have a header that stays fixed at the top of the page. The problem is when the user clicks on a link to another part of the same page, the link's target appears under the header. I'm not sure how to prevent this.
Edit: I ended up using JQuery to give internal links a smooth scroll, which eliminated this problem.
$("span.sect1, span.sect2").click(function(){
    var target = '#' + $(this).find("a").attr('href').match(/#(.*)$/)[1];
    var position = $(target).offset();
    $('html, body').animate({scrollTop: (position.top -40)}, "slow");
});
$("a.xref").click(function(){
    var target = '#' + $(this).attr('href').match(/#(.*)$/)[1];
    var position = $(target).offset();
    $('html, body').animate({scrollTop: (position.top -40)}, "slow");
});

Answer: Where before you might have:

Get here with #target

Try this:

Get here with #target

Comment: Unfortunately I need a solution that works by using CSS. The HTML is generated from docbook XML, and the links are to ids, not hidden anchors
Comment: Well, you could apply the CSS to the `h1`: `position: relative; top: -35px; padding-top: 35px;`
Comment: While that works, that technique also changes other parts of the page layout. For example, some headers have a background color and span across the page, and changing the padding on them like that increases their visible height. It's also difficult for me to anticipate all the objects on the page that might be the target of a link.
Comment: `:target` - this psuedo-class targets whatever element is the target of a link ;)


SQL - Conditions on two tables with a sum(case when)

Question: I have a code that gives me close to the answer I want.
Right now the code yields the growth between time for different estimates and it returns non null values for the different years. I would however need it to only sum values in which the underlying companies have values in both of the periods and not just in one of the periods.
 Select m.date_Month
    ,sum(case when y.date_year = 2016 then n.EBIT end) / sum(case when y.date_year = 2015 then n.EBIT end) - 1 as 'EBIT Growth 2015-2016'
 from EBIT as n
    inner join date_year as y on y.date_year_id = n.date_year_id
    inner join date_month as m on m.date_month_id = n.date_month_id
where n.EBIT<> 0  and m.date_month > '2012-11-30' and m.date_month < '2017-01-31'
 group by m.date_month
 order by m.Date_Month asc;

I'm guessing there is something that needs to be added in either the sum(case when ....) syntax or in the where clause.
A short example to show exactly what I desire:
Company_Id  Date_Year  Date_Month  Ebit
1           2015       2014-12-30  50
1           2016       2014-12-30  52
2           2015       2014-12-30  60
3           2015       2014-12-30  40
3           2016       2014-12-30  43

Right now the code looks at the table above and takes: (52+43)/(50+60+40)-1
I need it to only take: (52+43)/(50+40)-1
Hence the final output for this specific Date_Month would ideally be:
Date_Month    EBIT Growth 2015-2016
.....         ......
2014-12-30    0.0556
.....         ......

The current output (and the desired output for the code can be seen below, the values are however wrong since they include values which exist for 2015 but not for 2016 (and vice versa).
date_Month  2014-2015   2015-2016
2012-12-31  0.025866    NULL
2013-01-31  0.043509    NULL
2013-02-28  0.048632    NULL
2013-03-31  1.120582    NULL
2013-04-30  0.076691    NULL
2013-05-31  0.072184    NULL
2013-06-30  0.078506    NULL
2013-07-31  0.088014    NULL
2013-08-31  0.084344    NULL
2013-09-30  0.088520    NULL
2013-10-31  0.090181    NULL
2013-11-30  0.091335    NULL
2013-12-31  0.094102    0.989785
2014-01-31  0.094030    0.011348
2014-02-28  0.096986    0.024370
2014-03-31  0.096916    0.040109
2014-04-30  0.098773    0.044166
2014-05-31  0.099726    0.051751
2014-06-30  0.099677    0.063474
2014-07-31  0.099865    0.071188
2014-08-31  0.101077    0.073944
2014-09-30  0.101028    0.075055
2014-10-31  0.090556    0.079508
2014-11-30  0.083493    0.083621
2014-12-31  0.070896    0.088688
2015-01-31  0.072573    0.095857
2015-02-28  0.077159    0.102403
2015-03-31  0.082023    0.102581
2015-04-30  0.076842    0.096223
2015-05-31  0.088918    0.094773
2015-06-30  0.084905    0.093353
2015-07-31  0.075418    0.086845
2015-08-31  0.061566    0.085217
2015-09-30  0.051807    0.071888
2015-10-31  0.060045    0.066542
2015-11-30  0.072266    0.061107
2015-12-31  0.050182    0.055806
2016-01-31  NULL            0.023453
2016-02-29  NULL            0.029018
2016-03-31  NULL          0.011684
2016-04-30  NULL            0.007700
2016-05-31  NULL           0.012831
2016-06-30  NULL           0.001756
2016-07-31  NULL          -0.001628
2016-08-31  NULL          -0.001095
2016-09-30  NULL         -0.000649
2016-10-31  NULL          0.000707
2016-11-30  NULL          0.015307
2016-12-31  NULL          0.013374

Thanks to input this is the code that almost yields exactly what I want, but it does not include the 'Null' value seen in the example above:
SELECT
    m1.date_Month,
    SUM(n2.EBIT) /
    SUM(n1.EBIT) - 1 AS 'EBIT Growth 2014-2015',
    SUM(n3.EBIT) /
    SUM(n2.EBIT) - 1 AS 'EBIT Growth 2015-2016'
FROM EBIT AS n1
   INNER JOIN date_year AS y1 ON y1.date_year_id = n1.date_year_id
   INNER JOIN date_month AS m1 ON m1.date_month_id = n1.date_month_id
INNER JOIN EBIT AS n2
   INNER JOIN date_year AS y2 ON y2.date_year_id = n2.date_year_id
   INNER JOIN date_month AS m2 ON m2.date_month_id = n2.date_month_id
ON n1.Company_Id = n2.company_Id AND m1.date_month = m2.date_month
INNER JOIN EBIT AS n3
   INNER JOIN date_year AS y3 ON y3.date_year_id = n3.date_year_id
   INNER JOIN date_month AS m3 ON m3.date_month_id = n3.date_month_id
ON n2.Company_Id = n3.company_Id AND m2.date_month = m3.date_month
WHERE n1.EBIT <> 0 AND n2.EBIT <> 0 and n3.EBIT <> 0 AND y1.date_year = 2014 AND y2.date_year = 2015 and y3.date_year = 2016
GROUP BY m1.date_month
ORDER BY m1.Date_Month ASC;

I am using Microsoft Management Studio.
Comment: Edit your question and provide sample data and desired results.
Comment: I've Edited it slightly now, please let me know if you require more information to understand what my question is
Answer: Consider rewriting you query so that you inner join both periods (2016 and 2015) using criterias based on date_month and company_id which should filter rows where the company_id is missing in one of both periods.
SELECT
    m1.date_Month,
    SUM(n1.EBIT) /
    SUM(n2.EBIT) - 1 AS 'EBIT Growth 2015-2016'

FROM EBIT AS n1
   INNER JOIN date_year AS y1 ON y1.date_year_id = n1.date_year_id
   INNER JOIN date_month AS m1 ON m1.date_month_id = n1.date_month_id
INNER JOIN EBIT AS n2
   INNER JOIN date_year AS y2 ON y2.date_year_id = n2.date_year_id
   INNER JOIN date_month AS m2 ON m2.date_month_id = n2.date_month_id
ON n1.Company_Id = n2.company_Id AND m1.date_month = m2.date_month

WHERE n1.EBIT <> 0 AND n2.EBIT <> 0 AND y1.date_year = 2016 AND y2.date_year = 2015

GROUP BY m1.date_month
ORDER BY m1.Date_Month ASC;

Problems would arise with this solution when you have more than one record per company_id and month.

If you need to include NULL values, just use LEFT JOIN instead of INNER JOIN. In that case you get NULL values everywhere, where there is no matching record in following years for the specified companies, because x/NULL or NULL/x both equal to NULL and the SUM function ignores NULL values and equals to NULL only when all the summed values are NULL. So there will be all the records from the base year included in the resultset even if there were no relevant values in the following years.
...
LEFT JOIN EBIT AS n2
...
LEFT JOIN EBIT AS n3
...

You can also have the first join INNER and the second LEFT, if you need it, and start joining form the last relevant year (2016). In that case you will see only relavant comparsion 2016-2015 and also comparsions 2015-2014 of which some would be null.
Something like this:
SELECT
    m1.date_Month,
    SUM(n1.EBIT) /
    SUM(n2.EBIT) - 1 AS 'EBIT Growth 2016-2015',
    SUM(n2.EBIT) /
    SUM(n3.EBIT) - 1 AS 'EBIT Growth 2015-2014'
FROM EBIT AS n1
   INNER JOIN date_year AS y1 ON y1.date_year_id = n1.date_year_id
   INNER JOIN date_month AS m1 ON m1.date_month_id = n1.date_month_id
INNER JOIN EBIT AS n2
   INNER JOIN date_year AS y2 ON y2.date_year_id = n2.date_year_id
   INNER JOIN date_month AS m2 ON m2.date_month_id = n2.date_month_id
ON n1.Company_Id = n2.company_Id AND m1.date_month = m2.date_month
LEFT JOIN EBIT AS n3
   INNER JOIN date_year AS y3 ON y3.date_year_id = n3.date_year_id
   INNER JOIN date_month AS m3 ON m3.date_month_id = n3.date_month_id
ON n2.Company_Id = n3.company_Id AND m2.date_month = m3.date_month
                                 AND y3.date_year = 2014
WHERE y1.date_year = 2016 AND y2.date_year = 2015
GROUP BY m1.date_month
ORDER BY m1.Date_Month ASC;

Comment: thank you, This gives me exactly what I want for one column but when I add another column (following same approach) I can't get the 'Null' Values that I would like to have and hence I only get a time series in which all of the columns have data. Do you know if there is a way to make it so that we keep the same constraint for one time series (2015-2016) yet make it so that another time series can have null values etc. (2014-2015 in end and 2015-2016 in beginning since we will have more values for the beginning of 2014-2015 and more in the end for 2015-2016)
Comment: Thank you, Sadly the code does not give me 'Null' values (nor does changing all of the inner join to left join (or just some of them)). It is highly likely that something is a bit weird with my system cause I know that left join should work.

However if this query still does not check that the data used exists in the different time periods I can not use it. the optimal would be if there was a way to put the first code you put together with another identical code for another period and make a left join of that, maybe try to incorporate a view instead?

Thank you for you help!
Comment: @CedricVongheer Your system is allright, the problem is elsewhere. Check this answer https://stackoverflow.com/a/12467854/2224701. I have modified my second example and included 3rd filter in ON clause instead of WHERE clause - that was a mistake.
Comment: Thank you so much for the help, I've made the code work (although imperfectly perhaps) by following your detailed example and logic. I feel like I've at least partly gotten a better grasp of SQL through your help.


touch.phase == TouchPhase.Canceled not worked

Question: I'm tired to handle and solve issues related to multitouch. I'm using maximum 5 touches simultaneously but when two touches are down on two objects and I moved my fingers then that both touches fired TouchPhase.Ended event but not TouchedPhase.Canceled.
I want to fire TouchPhase.Canceled when my fingers are out of those objects.
if (touch.phase == TouchPhase.Began) {
   hitObject.GetComponent ().TouchDown (hitObject);
}

if (touch.phase == TouchPhase.Ended) {
   hitObject.GetComponent ().TouchExit (hitObject);
}

if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) {
   hitObject.GetComponent ().TouchStay (hitObject);
}

if (touch.phase == TouchPhase.Canceled) {
   print ("Touched canceled....");
   hitObject.GetComponent ().TouchExit (hitObject);
}

Comment: "Ended" means the user lifted his finger, this is the regular event you should handle. "Cancelled" means the touch was forcefully interrupted (incoming SMS, gesture recognizer handling the touch) and is rarely sent.
Comment: But i m used Unity. In my Screen One Object When i touch down on that object that it is detected when i drag my fingure of the out side of that detected object at that time i want to handle that event. How can i do that ?
Comment: Let me clarify, firstly you touch an object. Then you drag your finger until its not touching that object anymore. And you want to handle an event when your finger exits that object on drag. Am I right?
Comment: Look,I have one object on my screen.I use raycast for detecting that object.in hitObject i m stored that hittedObject and when my fingure touchdown on that object then it works. if i touchup my fingure from that hitted object that is also worked.when my fingure is stayed on that object or i m move my fingure on that hitted object that is also worked. but when during moving my fingure if it is move outside that object at that time TouchPhase.Canceled event should be fired. but that can not worked . That is my issue. How can i solved it ?
Comment: That isn't what TouchPhase.Canceled does. The TouchPhase refers to the user's finger physically touching the screen, it has no idea what your objects are or whether or not your user is touching the object.
Comment: I want to stop dragging/swapping finger (not moving) on that hitted object how can i do?
Answer: If i understand your comment correctly

Look,I have one object on my screen.I use raycast for detecting that object.in hitObject i m stored that hittedObject and when my fingure touchdown on that object then it works. if i touchup my fingure from that hitted object that is also worked.when my fingure is stayed on that object or i m move my fingure on that hitted object that is also worked. but when during moving my fingure if it is move outside that object at that time TouchPhase.Canceled event should be fired. but that can not worked . That is my issue. How can i solved it ?

and

I want to stop dragging/swapping finger (not moving) on that hitted object how can i do?

you are going to have to restrict the swiping based on the touch position.
var realWorldPos = Camera.main.ScreenToWorldPoint(touch.position);

if(realWorldPos.x < maximumXSwipePosition && realWorldPos.x > minimumXSwipePosition)
{
    //do the stuff you want to do
}
//otherwise, don't do it.


JavaScript: min & max values in very big array?

Question: How can I easily obtain the min and max values from a very big JavaScript Array (e.g 250 thousand numbers)?
I tried to use this method, but it does not work: JavaScript: min & max Array values?
I'm debugging in VisualStudio where I don't get any error, while in the browser I get "Maximum call stack size exceeded".
Example code:
var max = Math.max.apply(-Infinity, arr);
var min = Math.min.apply(Infinity, arr);

"arr" is my very big array.
Comment: First, first argument of apply is context. It should be `null` or `this`. Second you can always go back to custom for loop. That is the safest option
Comment: what's the problem with your code? In my chrome is working.
Comment: for me the code also works, what browser are you using ?
Comment: I tried using null, this or Math, and the effect is always the same.
Comment: @PAPP - I think it's worth mentioning what browser you are using so that others can have a chance of replicating your issue.
Comment: @evolutionxbox - I used it in Chrome, Firefox and Internet Explorer with the same result. It is important that this code works with smaller arrays (I tried with 65K elements).
Comment: One certainly safe way of doing this job is using `Array.prototype.reduce()`.
Comment: @PAPP this is interesting: might be a performance issue? What you mean with "doesn't work"?
Comment: @pietro909 I used Visual Studio as a debugger, and I did not have any error message. But now I checked using tools from the browser, and there is an error: "Maximum call stack size exceeded".
Comment: so you got it: there is a limit. Turns out that you can't do that.
Comment: I suspect that is using recursion under the hood.
Answer: For large arrays of mentioned sizes you can not use Math.min() or Math.max() safely. I believe this is how it should be done.

var arr = new Array(1000000).fill().map(_=> ~~(Math.random()*10000000)),
findMax = a => a.reduce((res,cur) => res < cur ? cur : res ,-Infinity);
console.log(findMax(arr));
Answer: It is working fine for me
var min = Math.min.apply(Math, array);
var max = Math.max.apply(Math, array);

Comment: I tried using null, this or Math, and the effect is always the same. Are you sure you tried to use it on such a large array as I described? Because this code works with smaller tables (I tried with 65K elements).
Comment: I didn't tried with large arrays, let me check once @PAPP
Comment: There is no guarantee when you need to pass arguments in the order of 150-300 K that you won't get stack overflow depending on the browser session. Large arrays can not be done by `Math.min()` or `Math.max()`


JSON substituindo informação com o mesmo nome

Question: Quero gravar dois ou mais nomes em um arquivo JSON. Porém, quando tento fazer, isso ele salva apenas a última informação.
Minha função:
async function grava_login(){
 fs.writeFile("data.json", JSON.stringify({name: "Mohamed Almaci",
name:"Masq"}),"utf8", async function(err){
 try{
  if(err){
   console.log(err);
  }
  else{
   console.log("The file was saved!");
  }
 }
 catch{
  console.log("Erro ao salvar dados no arquivo json!")
 }
})}

Como quero que o JSON fique:
{
  "name": "Mohamed almaci",
  "name": "Masq"
}

Como o JSON está:
{
  "name":"Masq"
}

Comment: Voce está sobreescrevendo o `name` ao fazer `name="Masq"`. Se voce atribuir outra chave, por exemplo `name1: "Masq"` , ele nao vai sobreescrever e entao vai ser salvo todo o objeto `{
  name: "Mohamed almaci",
  name1: "Masq"
}` no arquivo.
Comment: Percebi que estou sobreescrevendo porém vi gente fazendo do jeito que quero e funcionando, vi um exemplo mais era com email, e a pessoa conseguiu fazer o mesmo que quero, porém não era com node e era sobre outro tema então não consegui entender como fazer isso pelo node js com a lib fs.
Comment: Olhe este vídeo de exemplo https://youtu.be/iiADhChRriM minuto 8:44 perceba que ele usou name duas vezes, mas não consigo fazer isto. Já tentei de tudo quanto é forma.
Answer: Guilherme,
Para salvar um JSON com duas propriedades name, você pode criar um array e cada posição do array ser um objeto que contém a propriedade name e seu respectivo valor, exemplo:
[
  {
    "name":"Mohamed Almaci"
  },
  {
    "name":"Masq"
  }
]

Inclusive, no vídeo que você citou (8:44), ele segue essa ideia.

Com isso, seu código ficaria da seguinte forma:
const fs = require("fs");

async function grava_login() {
  fs.writeFile("data.json", JSON.stringify([{name: "Mohamed Almaci"},{name:"Masqx"}])
    , "utf8", async function(err) {
    if(err) {
      console.log(err);
    }
    else {
      console.log("The file was saved!");
    }
  });
}

grava_login();

Veja online: https://repl.it/repls/IvoryBruisedMachinecodeinstruction
Comment: :) não tinha usado o [ tinha tentado com chaves sem criar o array, obrigado.
Comment: Só não entendi o porquê no arquivo json dele não ficou com o [ e o meu ficou, mais funcionou!


cURL geto no response no error online server

Question: Hope anyone can help me out with this. I have tried to call external site using cURL but I get no error or response. Yet it works fine on local server but does not work on production server. I had started the call using file_get_contents() but fail online too. I talked to the hosting and they mentioned the problem is within codes. here is my codes can anyone help!?`
function send_with_curl($url, $data) {
   $data_string;
       //url-ify the data for the POST
    foreach ($data as $key => $value) { $data_string .= $key . '=' .  $value . '&';
}
rtrim($data_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, count($data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

//execute post
$result = curl_exec($ch);
if (!is_string($result) || !strlen($result)) {
    $result = "Failed to connect.";
}
//close connection
curl_close($ch);
return $result;
}

I also have another function that uses file_get_contents() and whichever I may use they work locally but fail online without an error I spent more than 4 hours trying to fix it with hosting guys until they finally said the error is within codes and they weren't familiar with those codes :(
function send_with_file($url, $context, $sender) {
global $database;
if (!$result = file_get_contents($url, false, $context)) {
    echo "Message sending failed, please check your internet.";
    exit ;
} else {
    //--UPDATING THE DATABASE------
    $sql_update = "SELECT * FROM users WHERE users_type='2'";
    $query_update = $database -> query($sql_update);
    while ($update = $database -> fetch_array($query_update)) {
        $update_user = $update['users_id'];
        if ($update_user == $sender) {

            if ($result === FALSE) {/* Handle error */
            }
        } else {

        }

    }
}
return $result;
}

Answer: Compare $result against false and then check curl_error()
Something like...
$result = curl_exec($ch);
if($result === false) {
    echo "Error in cURL : " . curl_error($ch);
}

Comment: it doesn't give any response! :'(
Comment: Are you sure the URL is actually returning anything?
Comment: pretty sure, cause on my local server I get the response from the URL! but on production server I get nothing and it fails to do the request
Comment: Mind sharing said URL?
Comment: http://184.108.40.206:8080/staronly/rapid.htm that is the url without passing any parameter it will return an error. but that error I don't even get from the hosting server but locally I get it!
Comment: hmmm.. I can access that URL just fine.. it says invalid client but still.. will think on it some more... is your server on amazon aws by chance... maybe getting ip blocked? (just trying to eliminate things)
Comment: nope it's on hostoople, it's so frustrating I spend more than 10hours on this thing without any clue of what wrong on the server or my codes. but so far my codes are fine as they work effectively locally but I'm wondering whether there is any thing I can do make them online
Comment: try this as a quick sanity check `echo file_get_contents('http://184.108.40.206:8080/staronly/rapid.htm');` do you get anything?
Comment: On my local server I get this Invalid clientName but online nothing!
Comment: I'm at work at the moment but I'll think on it and try some ideas when I'm home
Answer: There was no problem with the codes, I just traced the url I was trying to connect to and realized it takes too long to communicate with the hosting server.


Excel VBA Worksheets.codename gives an error

Question: I have a sheet(tab)name called "data", the sheetcodename is also "data"
When I use;
Cells(rij, "K") = Worksheets("data").Cells(1, "F")

It works fine but when I use;
Cells(rij, "I") = data.Cells(1, "F")

It gives an error.
Comment: You can find the appropriate sheet names and codenames in the project explorer. `Codename(SheetName)`. You can directly reference codenames, but you have to reference the worksheetnames like your first piece of code.
Comment: What is the error?
Comment: Error 91 during execution:
Object variable or block variable With is not set
Comment: Then `data` is not an sheet codename that actually exists.
Comment: See this link: http://ccvd.eu/i/vba.jpg
Comment: I cannot reproduce your problem.  Something else is going on outside of the code snippet you have shown.
Comment: The code works well in worksheets and in Thisworkbook. But not in a module.
Answer: If You declare and set "data" it will work:
Dim data As Worksheet

Set data = Sheets("data")

Cells(rij, "I") = data.Cells(1, "F")

Edit:
If You got 1 sheet You can easily go with:
Dim data As Worksheet

Set data = ThisWorkbook.Sheets(1)

Cells(rij, "I") = data.Cells(1, "F")

Comment: This does not work if the users change the tab name
Answer: You could follow the below:
Option Explicit

Sub test()

    Dim str As String

    'Get the value of the cell using Tab name
    str = ThisWorkbook.Worksheets("data").Range("A1").Value

    'Get the value of the cell using Code name
    str = data.Range("A10").Value

End Sub

Answer: Why don't you do :
Dim MySheet As worksheet

Set MySheet = ThisWorkbook.Sheets(1)

Cells(rij, "K") = MySheet.Cells(1, "F")

Cells(rij, "I") = MySheet.Cells(rij, "K")

Comment: I will use the codename because the user can change the tab name.
Comment: @Con I edited my code so you don't use sheets name, Does it work ?
Comment: If OP is worried about user changing tab name, they will be even more concerned about user moving sheet on different position :-)
Comment: @buran then there ls no viable solution as far as i know ;)
Comment: that is why they want to use CodeName instead - the most difficult for user to change it, although not impossible :-) The question is why it don't work as it should
Answer: I know the problem and have the solution.
I had declared several variables.
'Public cainA As Worksheet
'Public data As Worksheet
'Public eindblad As Worksheet

Sub reken(rij, kol, kolnaam)
Application.EnableEvents = False
Application.ScreenUpdating = False

And now made these as comments.
Now it works.
Thanks for all your support.


'"media_edit_action" plugin does not exist' error when performing update

Question: I get the following error after a database update. It looks like it completes the update by displaying Completed 8 of 8 but it doesn't run the updates. Any help is appreciated.

Failed: Drupal\Component\Plugin\Exception\PluginNotFoundException: The "media_edit_action" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of /srv/bindings/ae21023ced6d43099409c0fbbeded25e/code/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

This is what the updates need to run.
System module

Change plugin IDs of actions.
  Clear caches due to schema changes in core.entity.schema.yml.

Views module

Update dependencies for moved bulk field plugin.
  Add additional settings to the entity link field and convert node_path usage to entity_link.
  Add placeholder settings to string or numeric filters.
  Fix cache max age for table displays.
  Include views data table provider in views dependencies.
Answer: I believe that action at some point became deprecated and was removed from the media_entity module.  However, the configuration lingered and is blocking Drupal update from completing successfully.
What worked for me was to go the the Admin > Configuration > Development > Configuration Synchronization > Updates Report (menu tab).
If you view the Full Report, then you can see that the config for the media_edit_action is still present.
Use the pulldown menu on the right to delete that config.

When you run update again, then it should complete successfully.
Hope this helps!
Comment: Thank Rich, it worked. I just needed to install the Config_update module in order for the Updates Report tab to show up. https://ftp.drupal.org/files/projects/config_update-8.x-1.5.tar.gz