Conversão de dados usando ComboBox

Question: Olá, Estou com dificuldade para tratar um erro no meu programa.
Tenho duas comboBox dentro de um painel de cadastro. Ao executa ja aparece a lista de produtos e clientes, porem o campo de código não esta preenchendo.
Criei um evento de PopupMenuWillBecomeInvisible em cada comboBox.
private void preencherCodigoClientePeloCombobox(){

        modelCliente  = controllerCliente.getClienteController(jcbNomeCliente.getSelectedItem().toString());
        jtfCodigoCliente.setText(String.valueOf(modelCliente.getIdCliente()));
    }

    private void preencherCodigoProdutoPeloCombobox(){

            modelProdutos = controllerProdutos.retornarProdutoController(jcbNomeProduto.getSelectedItem().toString());
            jtfCodigoProduto.setText(String.valueOf(modelProdutos.getIdProduto()));

    }

E o java pedi para fazer a conversão de String para inteiro, Fiz asssim:

private void preencherCodigoClientePeloCombobox(){

        modelCliente  = controllerCliente.getClienteController(Integer.parseInt(jcbNomeCliente.getSelectedItem().toString()));
        jtfCodigoCliente.setText(String.valueOf(modelCliente.getIdCliente()));
    }

    private void preencherCodigoProdutoPeloCombobox(){

            modelProdutos = controllerProdutos.retornarProdutoController(Integer.parseInt(jcbNomeProduto.getSelectedItem().toString()));
            jtfCodigoProduto.setText(String.valueOf(modelProdutos.getIdProduto()));

    }

Só que continua com erro:
run:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "teste"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at view.ViewVendas.preencherCodigoClientePeloCombobox(ViewVendas.java:538)
    at view.ViewVendas.<init>(ViewVendas.java:42)
    at view.ViewVendas$11.run(ViewVendas.java:531)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Alguma solução possivel?
Answer: Você está com um NumberFormatException
Esta exceção está sendo lançada quando você faz a conversão de String pra o tipo inteiro int
Para evitar que esse problema ocorra você deve se certificar de que a String que você está convertendo pode ser transformada em int. Verifique se a sua String não possui espaços, caracteres especiais, letras qualquer coisa que não seja um número.
Note que você tentou converter a palavra "teste" pra int, isso nunca vai dar certo pois esta palavra não pode ser convertida em um número.
Você deveria passar uma string contendo números apenas.
String stringDeNumeros = "12345";
Int conversao = Integer.parseInt(string DeNumeros);

Isso funciona.
Mas o código abaixo não:
String stringDeNumeros = "teste12345";
Int conversao = Integer.parseInt(string DeNumeros);

Comment: tenho esses metodos que preencher minha comboBox com meus dados.

Conversão de dados usando ComboBox


Optimal median function

Question: I was experimenting with some code in an attempt to answer Generic Method to find the median of 3 values and was trying to ensure that the compareTo method was called a minimum number of times and to maximise the efficiency of the code and came up with this:
// Flattens the results of a compareTo to -1, 0, 1
static int sign(int x) {
    return x < 0 ? -1 : x == 0 ? 0 : 1;
}

// Use an enum to help.
enum ABC {

    A() {

                @Override
                <T> T which(T a, T b, T c) {
                    return a;
                }

            },
    B() {

                @Override
                <T> T which(T a, T b, T c) {
                    return b;
                }

            },
    C() {

                @Override
                <T> T which(T a, T b, T c) {
                    return c;
                }

            },
    INSANE() {

                @Override
                <T> T which(T a, T b, T c) {
                    // Something like a < b and b < c but c < a
                    return null;
                }

            };

    abstract <T> T which(T a, T b, T c);
}

// Straight lookup.
private static final ABC[][][] median = {
    { // a < b
        { // b < c
            // a < c
            ABC.B,
            // a == c
            ABC.INSANE,
            // a > c
            ABC.INSANE
        },
        { // b == c
            // a < c
            ABC.B,
            // a == c
            ABC.INSANE,
            // a > c
            ABC.INSANE
        },
        { // b > c
            // a < c
            ABC.C,
            // a == c
            ABC.A,
            // a > c
            ABC.A
        }
    },
    { // a == b
        { // b < c
            // a < c
            ABC.B,
            // a == c
            ABC.INSANE,
            // a > c
            ABC.INSANE
        },
        { // b == c
            // a < c
            ABC.INSANE,
            // a == c
            ABC.B,
            // a > c
            ABC.INSANE
        },
        { // b > c
            // a < c
            ABC.A,
            // a == c
            ABC.B,
            // a > c
            ABC.A
        }
    },
    { // a > b
        { // b < c
            // a < c
            ABC.A,
            // a == c
            ABC.A,
            // a > c
            ABC.C
        },
        { // b == c
            // a < c
            ABC.INSANE,
            // a == c
            ABC.INSANE,
            // a > c
            ABC.B
        },
        { // b > c
            // a < c
            ABC.INSANE,
            // a == c
            ABC.INSANE,
            // a > c
            ABC.B
        }
    }
};

private static <T extends Comparable> T median(T a, T b, T c) {
    System.out.print(" ab=" + sign(a.compareTo(b)) + " bc=" + sign(b.compareTo(c)) + " ac=" + sign(a.compareTo(c)));
    // Least number of comparisons.
    return median[sign(a.compareTo(b)) + 1][sign(b.compareTo(c)) + 1][sign(a.compareTo(c)) + 1]
            .which(a, b, c);
}

// My test case.
private static <T extends Comparable> T median2(T a, T b, T c) {
    List<T> medianHelper = Arrays.asList(a, b, c);

    Collections.sort(medianHelper);

    return medianHelper.get(1);
}

public void test() {
    for (int a = -5; a <= 5; a += 5) {
        for (int b = -3; b <= 3; b += 3) {
            for (int c = -1; c <= 1; c++) {
                System.out.print("(" + a + "," + b + "," + c + ")");
                Integer m = median(a, b, c);
                Integer m2 = median2(a, b, c);
                System.out.print(" -> " + m + " & " + m2);
                if (m != m2) {
                    System.out.print(" <-- WRONG");
                }
                System.out.println();
            }

        }
    }
}

To get it working I just used the sort them and pick the middle one technique and manually tweaked my matrix until it returned the same result.
Although this seems to work it clearly does not cover all of the possibilities for when compareTo is unstable (e.g. a < b && b < c && c < a) but I don't think that is too important.
Is there some mechanism I could use to correctly generate the matrix? Ideally one that could also be used to generate the min and max matrices too.
Comment: Note: You also have `Integer.signum(i)`...
Comment: @assylias - I'd forgotten that - thankyou.
Comment: that  ... may the the most convoluted, obscure piece of core i have seen during my entire lifetime - and i have seen HTML fragments inside of  embedded C code which creates its own webserver, already - thanks for sharing this marvelous piece of dizzying mystery.

If i might ask : is this some sort of obfuscation attempt?
Comment: @specializt - No - it turns a median function into exactly three compares (provably the minimum for a `median` algorithm) and a single array lookup and some trivial math. It could cut milliseconds off a method which, if used billions of times would save years of computation time. It's called `optimal`, or an attempt of it.
Comment: so ... you were trying to improve performance of a common algorithm (median), is that about right?
Comment: @specializt - not just improve, optimize.
Comment: in that case you will have to exchange these resursive function calls for an iterative approach - recursion is _always_ slower than (well designed) iteration, thats an architectural design result.
Answer: If you just want to call compareTo only 3 times (I don't think you can make it work with 2 calls), why not a simple nested if/else:
public static <T extends Comparable> T median(T a, T b, T c) {
  if (a.compareTo(b) <= 0) {
    if (a.compareTo(c) <= 0) {
      return b.compareTo(c) <= 0 ? b : c; //a <= b && a <= c, return min(b, c)
    } else {
      return a;  //c < a <= b, return a
    }
  } else { // b < a
    if (a.compareTo(c) <= 0) {
      return a; // b < a <= c, return a
    } else {
      return b.compareTo(c) <= 0 ? c : b; //b  c, return max(b, c)
    }
  }
}

Answer: After much consideration I abandoned the table lookup technique and went for code that was provably optimal.
public static <T extends Comparable> T median(T a, T b, T c) {
  switch (Integer.signum(a.compareTo(b))) {
    case -1:
      // a < b
      switch (Integer.signum(b.compareTo(c))) {
        case -1:
          // b < c
          return b;

        case 0:
          // b = c - pick one.
          return b;

        case 1:
          // b > c
          return max(a, c);

        default:
          // Should never happen.
          return null;

      }

    case 0:
      // First two the same - median must be one of them - just pick one.
      return b;

    case 1:
      // a > b
      switch (Integer.signum(a.compareTo(c))) {
        case -1:
          // a < c
          return a;

        case 0:
          // a = c - pick one.
          return a;

        case 1:
          // a > c
          return max(b, c);

        default:
          // Should never happen.
          return null;

      }

    default:
      // Should never happen.
      return null;

  }
}

public static <T extends Comparable> T min(T a, T b, T c) {
  switch (Integer.signum(a.compareTo(b))) {
    case -1:
      // a  b
      return min(b, c);

    default:
      return null;

  }
}

public static <T extends Comparable> T max(T a, T b, T c) {
  switch (Integer.signum(a.compareTo(b))) {
    case -1:
      // a  b
      return max(a, c);

    default:
      return null;

  }
}

public static <T extends Comparable> T min(T a, T b) {
  switch (Integer.signum(a.compareTo(b))) {
    case -1:
      // a  b
      return b;

    default:
      return null;

  }
}

public static <T extends Comparable> T max(T a, T b) {
  switch (Integer.signum(a.compareTo(b))) {
    case -1:
      // a  b
      return a;

    default:
      return null;

  }
}

private static void test(int a, int b, int c, String results) {
  boolean ok = false;
  int m = median(a, b, c);
  for (int i = 0; i < results.length(); i++) {
    switch (results.charAt(i)) {
      case 'A':
        if (m == a) {
          ok = true;
        }
        break;
      case 'B':
        if (m == b) {
          ok = true;
        }
        break;
      case 'C':
        if (m == c) {
          ok = true;
        }
        break;
    }
  }
  if (!ok) {
    System.out.println("Failed median(" + a + "," + b + "," + c + ") = " + m);
  }
}

public static void main(String args[]) {
  try {
    test(0, 0, 0, "ABC");
    test(0, 0, 1, "AB");
    test(0, 1, 0, "AC");
    test(1, 0, 0, "BC");
    test(1, 1, 0, "AB");
    test(1, 0, 1, "AC");
    test(0, 1, 1, "BC");
    test(0, 1, 2, "B");
    test(0, 2, 1, "C");
    test(1, 0, 2, "A");
    test(1, 2, 0, "A");
    test(2, 1, 0, "B");
    test(2, 0, 1, "C");
  } catch (Throwable t) {
    t.printStackTrace(System.err);
  }
}

Comment: I don't think this works: if c < b < a, your code will return a.
Comment: @assylias - That made it less elegant. Added some test cases too. Thanks for the heads-up.
Answer: I eventually rolled my own by starting with a matrix filled with INSANE and fixing all the places that did not match the sort and pick one method.
This also required a print method that prints the matrix as Java source.
// Flattens the results of a compareTo to -1, 0, 1
static int sign(int x) {
    return Integer.signum(x);
}

// Use an enum to help.
enum ABC {

    A() {

                @Override
                <T> T which(T a, T b, T c) {
                    return a;
                }

            },
    B() {

                @Override
                <T> T which(T a, T b, T c) {
                    return b;
                }

            },
    C() {

                @Override
                <T> T which(T a, T b, T c) {
                    return c;
                }

            },
    INSANE() {

                @Override
                <T> T which(T a, T b, T c) {
                    // Something like a < b and b < c but c < a
                    return null;
                }

            };

    abstract <T> T which(T a, T b, T c);
}

private static <T extends Comparable> T byLookup(ABC[][][] matrix, T a, T b, T c) {
    // Least number of comparisons.
    return matrix[sign(a.compareTo(b)) + 1][sign(b.compareTo(c)) + 1][sign(a.compareTo(c)) + 1]
            .which(a, b, c);
}

private static <T extends Comparable> T bySort(T a, T b, T c, int which) {
    // Sort and pick one.
    List<T> medianHelper = Arrays.asList(a, b, c);

    Collections.sort(medianHelper);

    return medianHelper.get(which);
}

private void checkMatrix(ABC[][][] matrix, int a, int b, int c, int which) {
    // Use the two functions.
    Integer m1 = byLookup(matrix, a, b, c);
    Integer m2 = bySort(a, b, c, which);
    if (!Objects.equal(m1, m2)) {
        // Wrong! Fix it.
        matrix[sign(Integer.compare(a, b)) + 1][sign(Integer.compare(b, c)) + 1][sign(Integer.compare(a, c)) + 1]
                = m2 == a ? ABC.A : m2 == b ? ABC.B : ABC.C;
    }
}

public void buildMatrix(String name, int which) {
    // All INSANE to start with.
    ABC[][][] matrix = new ABC[3][3][3];
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[0].length; j++) {
            for (int k = 0; k < matrix[0][0].length; k++) {
                matrix[i][j][k] = ABC.INSANE;
            }
        }
    }
    // Test it.
    for (int a = -5; a <= 5; a += 5) {
        for (int b = -3; b <= 3; b += 3) {
            for (int c = -1; c <= 1; c++) {
                checkMatrix(matrix, a, b, c, which);
            }

        }
    }
    // Print it.
    printMatrixAsJava(name, matrix);
}

public void buildMatrices() {
    buildMatrix("min", 0);
    buildMatrix("median", 1);
    buildMatrix("max", 2);
}

static final String CR = "\r\n";

private void printMatrixAsJava(String name, ABC[][][] m) {
    StringBuilder s = new StringBuilder();
    String[] op = {"<", "=", ">"};
    s.append("private static final ABC[][][] ").append(name).append(" = {" + CR);
    for (int a = 0; a < 3; a++) {
        s.append("\t{ // a ").append(op[a]).append(" b" + CR);
        for (int b = 0; b < 3; b++) {
            //{ // b < c
            s.append("\t\t{ // b ").append(op[b]).append(" c" + CR);
            for (int c = 0; c < 3; c++) {
                //                // a < c
                //ABC.INSANE,

                s.append("\t\t\t// a ").append(op[c]).append(" c" + CR);
                s.append("\t\t\tABC.").append(m[a][b][c].name()).append("," + CR);
            }
            s.append("\t\t}," + CR);
        }
        s.append("\t}," + CR);
    }
    s.append("};" + CR);
    System.out.println(s);
}

This results in:
// The lookups generated by the above.
private static final ABC[][][] min = {
  { // a < b
    { // b < c
      // a < c
      ABC.A,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b = c
      // a < c
      ABC.A,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b > c
      // a < c
      ABC.A,
      // a = c
      ABC.A,
      // a > c
      ABC.C,},},
  { // a = b
    { // b < c
      // a < c
      ABC.A,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b = c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.A,
      // a > c
      ABC.INSANE,},
    { // b > c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.C,},},
  { // a > b
    { // b < c
      // a < c
      ABC.B,
      // a = c
      ABC.B,
      // a > c
      ABC.B,},
    { // b = c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.B,},
    { // b > c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.C,},},};

private static final ABC[][][] median = {
  { // a < b
    { // b < c
      // a < c
      ABC.B,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b = c
      // a < c
      ABC.B,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b > c
      // a < c
      ABC.C,
      // a = c
      ABC.A,
      // a > c
      ABC.A,},},
  { // a = b
    { // b < c
      // a < c
      ABC.A,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b = c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.A,
      // a > c
      ABC.INSANE,},
    { // b > c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.A,},},
  { // a > b
    { // b < c
      // a < c
      ABC.A,
      // a = c
      ABC.A,
      // a > c
      ABC.C,},
    { // b = c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.B,},
    { // b > c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.B,},},};

private static final ABC[][][] max = {
  { // a < b
    { // b < c
      // a < c
      ABC.C,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b = c
      // a < c
      ABC.B,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b > c
      // a < c
      ABC.B,
      // a = c
      ABC.B,
      // a > c
      ABC.B,},},
  { // a = b
    { // b < c
      // a < c
      ABC.C,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.INSANE,},
    { // b = c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.A,
      // a > c
      ABC.INSANE,},
    { // b > c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.A,},},
  { // a > b
    { // b < c
      // a < c
      ABC.C,
      // a = c
      ABC.A,
      // a > c
      ABC.A,},
    { // b = c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.A,},
    { // b > c
      // a < c
      ABC.INSANE,
      // a = c
      ABC.INSANE,
      // a > c
      ABC.A,},},};

I would still be interested in a method that is not quite so strangely self-referential.
Comment: OMG! There *has* to be a better way!

Optimal median function


ifstream gcount returns 0 on getline string overload

Question: I'm finding that gcount on an ifstream object after a call to
  getline(istream &, string &)

returns 0.
Is this supposed to be the case?
Answer: Yes, gcount() is supposed to return the number of characters extracted by the last unformatted input operation performed on the object.
getline() is listed in the functions supposed to updated gcount(),  but it is the member getline() of a stream and not the string getline().
In case of doubt, this link tells it black on white: Behaves as UnformattedInputFunction, except that input.gcount() is not affected.


Calculating Conditional Values for Exponential Distribution

Question: For 2 numbers which are exponentially distributed with rate 3, I need to calculate:
the expected value of the lowest number given that both numbers are above 1/3
Answer: Because of the memorylessness of this distribution, you can just find the expected value of the minimum without the condition that they are greater than $1/3$, and then add $1/3$ to it.  (If you don't know about this, then (1) Google the word memorylessness, and (2) if you're taking a course on this material, look for it in your notes.)
$\min\{X_1,X_2\} > x$ if and only if both $X_1>x$ and $X_2>x$.  If the two random variables $X_1$ and $X_2$ are independent, then the probability that both of these events occur is just the product of their two probabilities: $\Pr(X_1>x\  \&\  X_2>x)= \Pr(X_1>x)\Pr(X_2>x) = e^{-3x}e^{-3x} = e^{-6x}$.  So the CDF of the minimum is $F(x) = 1-e^{-6x}$.  Differentiate that to get the density function $f(x)$, then find $\mathbb{E}(\min) = \displaystyle\int_0^\infty x f(x) \; dx$.
Comment: @Jeeyan : Could you "accept" my answer (i.e. click on the check mark on the left)?
Comment: +1 from me.  Your answer helped me think through a question I've had for some time.  Thanks.


Determine whether $\sum_{n=1}^{\infty} \frac{i^n}{\sqrt{n}}$ converges

Question: I am not sure if what I have done is correct:
I compare $\frac{i^n}{\sqrt{n}}$ with $\frac{(-1)^n}{\sqrt{n}}$ and have $  0\le \frac{i^n}{\sqrt{n}} \le \frac{(-1)^n}{\sqrt{n}}$ (However, I am not sure if this is correct).
By the Leibniz test, since $\frac{1}{\sqrt{k+1}} \le \frac{1}{\sqrt{k}}$ and since $\frac{1}{\sqrt{k}} \rightarrow 0$ as $k \rightarrow \infty$, I have that the original series converges. Would this be a correct way to show this?
Comment: Why not just break the series up into its real and imaginary parts?
Comment: Be careful. Inequalities make no sense with complex numbers.
Comment: Yes ${}{}{}{}{}$
Comment: @RonGordon - ahh right. Breaking it up into real and imaginary parts I get: $$ \sum_{n=1}^{\infty} \frac{i^n}{\sqrt{n}} = \sum_{n=1}^{\infty} (-1)^n \frac{1}{\sqrt{2n}} + \sum_{n=0}^{\infty} (-1)^n \frac{i}{\sqrt{2n+1}}$$ Then pulling out the constants and using Leibniz on both, I get convergence. Would that be correct?
Comment: Both sums converge and their values expressed simply in terms of  $\zeta$ functions.
Answer: The sequence of the real parts is
$$0,\frac{-1}{\sqrt 2},0,\frac 12,0,\frac{-1}{\sqrt 6},0,\ldots$$
and of the imaginary parts
$$1,0,\frac{-1}{\sqrt 3},0,\frac 1{\sqrt 5},0,\ldots$$
And the series corresponding to both sequences converge, by alternating series criterion (zeroes can clearly be ignored). Therefore, the series converges.


Foreach - Paginação com imagens

Question: Estou tentando exibir imagens, ao invés de números, na paginação.
Preciso de ajuda para colocar dentro do for essas imagens que estão vindo da variavel $aImages no foreach,
       $maximo = 1;
        $pagina = isset($_GET['pagina']) ? ($_GET['pagina']) : '1';
        $pagina2 = $pagina + 1;
        $inicio = $pagina - 1;
        $inicio = $maximo * $inicio;

        //CONSULTA PARA CONTAR TODOS REGISTROS
        $strCount = "SELECT COUNT(*) AS 'total_images' FROM posts, images
    WHERE posts.id_posts = images.posts_ID
    AND slug='".$_GET['slug']."'";
            $varstrCount = $crud->verdados($strCount);
            $total = 0;
            if(count($varstrCount)){
                foreach ($varstrCount as $row) {
                        $total = $row["total_imagens"];
                }
            }

            //CONSULTA PARA LIMITAR OS REGISTROS NA PAGINAÇÃO
            $resultado =  "SELECT * FROM posts, images
                         WHERE posts.id_post = images.posts_ID
                         AND slug='".$_GET['slug']."' ORDER BY id_posts LIMIT $inicio,$maximo";

            //EXECUTA A CONSULTA
            $varresultado = $crud->verdados($resultado);

            $max_links = 10;
            $previous = $pagina - 1;
            $next = $pagina + 1;
            $pgs = ceil($total / $maximo);

         //CONSULTA PARA AGRUPAR IMAGENS RELACIONADAS AO ID

          $stmt = $DB_con->prepare("SELECT
                                  posts.*,
                                  COUNT(0) total,
                                  GROUP_CONCAT(dir_image SEPARATOR '|') images
                                  FROM
                                    posts
                                 INNER JOIN images ON (posts.id_post = images.post_id )
                                 WHERE
                                   slug=:slug
                                 GROUP BY
                                 id_post
                                  ");
         //EXECUTA A CONSULTA
         $stmt->execute(array(":slug"=>$_GET['slug']));

         while($row=$stmt->fetch(PDO::FETCH_ASSOC))
         {
             $aImages = explode('|', $row['images']);

           for($i=$pagina-$max_links; $i <= $pgs; $i++) {
               foreach ($aImages as $sImage) {
               echo "";  ;

               }

            }

}

A ideia é ter esse resultado final:

Essas são a tabelas no DB:
Tabela IMAGES esta assim:
id_images | dir_image | post_id
1           image1.jpg  1
2           image2.jpg  1
3           image3.jpg  1
4           image4.jpg  1
5           image5.jpg  2
6           image6.jpg  2
7           image7.jpg  2
8           image8.jpg  2

Tabela POSTS:
id_post | slug          | title
1         title_post      Title Post
2         title_post_2    Title Post 2

Como exemplo a variavel $aImages tem 5 imagens vindas do DB, a ordem imprime corretamente mas cada imagem imprime repetidamente 15 vezes não entendi o motivo, preciso que cada uma imprima apenas uma vez.
Agradeço ajuda
Comment: o for() de dentro está imprimindo a imagem do for each de fora várias vezes. Precisa dele? Se precisa, precisa repensar sua paginação. Eu acho que não é o caso de usar foreach se é pra paginar. E outra coisa, $maximo tem que pegar o tamanho de $aImages.
Comment: Obrigada @Bacco o `for` é responsavel por adicionar o numero da paginação `$i`, não sei como fazer isso sem o for
Answer:
Nota: Esta resposta foi postada para uma edição anterior da pergunta.

Segue um exemplo bem simples e didático de paginação, para servir de exemplo:
$imagens = '/1.jpg|/2.jpg|/3.jpg|/4.jpg|/5.jpg|/6.jpg|/7.jpg|/8.jpg';
$aImages = explode( '|',  $imagens );

$porPagina = 3;
$total = count( $aImages );
$paginas = ceil( $total / $porPagina );

for( $pagina = 0; $pagina < $paginas; ++$pagina ) {
   echo 'Pagina ' . ( $pagina + 1 ) . '
' . PHP_EOL;

   $offset = $pagina * $porPagina;
   for( $item = $offset ; $item < $total && $item < $offset + $porPagina; ++$item ) {
       echo '' . PHP_EOL;
   }
}

Veja funcionando no IDEONE.
É claro que no caso, você vai ter que adaptar à situação real do seu código. Se for mostrar apenas uma página por vez, basta eliminar o for( $pagina de fora, e definir a variável externamente.
Comment: Obrigada @Bacco seu codigo é limpo objetivo e funcional, mas no meu caso eu aproveito algumas variaveis em outras partes do projeto. Atualizei a pergunta para vc ter uma noção melhor do que estou fazendo
Comment: Basicamente eu fiz alguns nomes pra ilustrar o que é cada coisa. Creio que basta você substituir as coisas pelos nomes certos, que vai funcionar. O simples fato de tirar o loop de fora, e pegar o $pagina do slug já faz o que você pretende. O loop de fora foi só pra você ver o de dentro em funcionamento (e ver como calculei o offset para determinar os ítens da página atual)
Comment: PS: Se não é uma "Paginação" de verdade, e quer mostrar todas as imagens, só fazer o que eu falei nos comentários: por o foreach dentro do for.
Comment: Com o foreach dentro do for aparece 1 imagem por vez na ordem certa mas repetindo varias vezes a sequencia de 5 imagens
Comment: Ja com o for dentro do foreach aparece cada imagem 15 vezes mas sequencia tbm certa
Comment: Não pode misturar o while com o for. Você pode usar o while para montar um array, e usar esse array no for (mas não dentro do while). E dentro do for que vai usar o explode (senão, o array vai ser sempre o mesmo).
Comment: è que dentro do while tem outras parte html e php que estou imprimindo conforme a consuldo do DB como titulo, slug, conteudo, etc. A paginação de imagens esta dentro do conteudo, então se tiro o while desconfigura todo o restante e até mesmo a propria paginação

Foreach - Paginação com imagens


Saving listview items to notepad

Question: I'm trying to save the items in my listview in a notepad, my code works however I'm getting the controls not the item itself
Here's my code:
File.AppendAllText(str_LogsDirectory + @"\" + DateTime.Now.ToString("MMMM dd, yyyy") + ".txt" , list_log.Items.ToString());

Comment: You're calling `ToString` on the collection - not on each item in the collection.
Comment: You got to loop through items. Also it is recommended to use `Path.Combine` for combining path.
Comment: @HassanNisar Ow, right I forgot the index of the item
Answer: You're calling ToString() on a ListViewCollection, which just returns the type of object. That's not what you want...
Assuming your ListView is just a list of strings (I don't know what the actual data type is that you're populating it with), try this:
var logDir = Path.Combine(str_LogsDirectory, DateTime.Now.ToString("MMMM dd, yyyy") + ".txt");

File.AppendAllText(logDir, String.Join(",", list_log.Items.Cast<string>()));

It will generate a comma-delimited string of all the items and append that to your file. If you're using a more complicated class to populate the ListView, then you'll have to do a little more work than this.
Comment: Quick question, how do I break line while appending it in notepad `\n` or `Environment.NewLine` doesn't seem to work.
Answer: string sPath = System.IO.Path.Combine(str_LogsDirectory, DateTime.Now.ToString("MMMM dd, yyyy") + ".txt");

using(System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath))
{
   foreach(var item in list_log.Items)
   {
       SaveFile.WriteLine(item.ToString());
   }
}

UPDATE (To include sub items of the ListView):
using(System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath))
{
   foreach(ListViewItem item in list_log.Items)
   {
       string sLine = item.ToString();

       for(int i=0; i<item.SubItems.Count;i++)
       {
            sLine += item.SubItems[i].Text;
       }

       SaveFile.WriteLine(sLine);
   }
}

Note: Include space between items according to your requirement.
Comment: It only gets 1 column in my listview.

Saving listview items to notepad


Calibrate against multi-dimensional population totals using the survey package?

Question: Is there a way to calibrate against multidimensional control totals using the survey package? I have been able to estimate poststratification weights, but now I'm stuck with the calibration. (I have a clustered design and need the weights to stay the same within each cluster.) Do I have to recode all combinations into a new attribute?
> df <- data.frame(id=c(1,1,1,2,2,3,4,5,5),
+                  h=factor(c(1,1,1,0,0,1,0,1,1)),
+                  p=factor(c(1,0,1,0,1,0,0,0,1)))
>
> df
  id h p
1  1 1 1
2  1 1 0
3  1 1 1
4  2 0 0
5  2 0 1
6  3 1 0
7  4 0 0
8  5 1 0
9  5 1 1
> des <- svydesign(id=~id, data=df)
Warning message:
In svydesign.default(id = ~id, data = df) :
  No weights or probabilities supplied, assuming equal probability
> pop <- xtabs(Freq~., data.frame(h=factor(c(0, 1, 0, 1)),
+                                 p=factor(c(0, 0, 1, 1)),
+                                 Freq=c(40, 35, 25, 10)))
> pop
   p
h    0  1
  0 40 25
  1 35 10
>
> ps <- postStratify(des, strata=~h*p, population=pop)
> weights(ps)
[1]  3.333333 11.666667  3.333333 20.000000 25.000000
[6]  11.666667 20.000000 11.666667  3.333333

The documentation and Lumley's "survey book" both don't show how to do this and if it's possible at all.
Answer: The documentation contains a small hint on how the names of the population vector for calibrate() should be formed: They are compared with the results of model.matrix(). The question remains how to derive a proper population vector from a table of totals like the one passed to postStratify().
I use a special call to model.matrix() to convert a totals table to a population vector. The main idea is to compute a model.matrix() from the totals table plus a Freq column, to scale the matrix contents by the Freq column and then to sum up column-wise. This results exactly in the population vector. Please see the complete example below for details.
> library(survey)

Attaching package: 'survey'

The following object(s) are masked from 'package:graphics':

    dotchart

> df <- data.frame(id=c(1,1,1,2,2,3,4,5,5,6,6,6,7,7,7)
+                  , h=factor(c(1,1,1,0,0,1,0,1,1,0,0,0,0,0,0))
+                  , p=factor(c(1,0,1,0,1,0,0,0,1,1,0,1,1,0,0))
+                  , q=factor(c(0,0,1,1,1,0,1,1,1,0,0,1,1,1,0))
+                  )
> df$hp <- do.call(interaction, df[, c('h', 'p')])
    > df$hq <- do.call(interaction, df[, c('h', 'q')])
> df$pq <- do.call(interaction, df[, c('p', 'q')])
    > df$hpq <- do.call(interaction, df[, c('h', 'p', 'q')])
> df
   id h p q  hp  hq  pq   hpq
1   1 1 1 0 1.1 1.0 1.0 1.1.0
2   1 1 0 0 1.0 1.0 0.0 1.0.0
3   1 1 1 1 1.1 1.1 1.1 1.1.1
4   2 0 0 1 0.0 0.1 0.1 0.0.1
5   2 0 1 1 0.1 0.1 1.1 0.1.1
6   3 1 0 0 1.0 1.0 0.0 1.0.0
7   4 0 0 1 0.0 0.1 0.1 0.0.1
8   5 1 0 1 1.0 1.1 0.1 1.0.1
9   5 1 1 1 1.1 1.1 1.1 1.1.1
10  6 0 1 0 0.1 0.0 1.0 0.1.0
11  6 0 0 0 0.0 0.0 0.0 0.0.0
12  6 0 1 1 0.1 0.1 1.1 0.1.1
13  7 0 1 1 0.1 0.1 1.1 0.1.1
14  7 0 0 1 0.0 0.1 0.1 0.0.1
15  7 0 0 0 0.0 0.0 0.0 0.0.0
>
> des <- svydesign(id=~id, data=df)
Warning message:
In svydesign.default(id = ~id, data = df) :
  No weights or probabilities supplied, assuming equal probability
>
> pop <- data.frame(h=factor(c(0, 1, 0, 1, 0, 1, 0, 1)),
+                   p=factor(c(0, 0, 1, 1, 0, 0, 1, 1)),
+                   q=factor(c(0, 0, 0, 0, 1, 1, 1, 1)),
+                   Freq=c(40, 35, 25, 35, 45, 30, 30, 30))
> pop$hp <- do.call(interaction, pop[, c('h', 'p')])
    > pop$hq <- do.call(interaction, pop[, c('h', 'q')])
> pop$pq <- do.call(interaction, pop[, c('p', 'q')])
    > pop$hpq <- do.call(interaction, pop[, c('h', 'p', 'q')])
> pop
  h p q Freq  hp  hq  pq   hpq
1 0 0 0   40 0.0 0.0 0.0 0.0.0
2 1 0 0   35 1.0 1.0 0.0 1.0.0
3 0 1 0   25 0.1 0.0 1.0 0.1.0
4 1 1 0   35 1.1 1.0 1.0 1.1.0
5 0 0 1   45 0.0 0.1 0.1 0.0.1
6 1 0 1   30 1.0 1.1 0.1 1.0.1
7 0 1 1   30 0.1 0.1 1.1 0.1.1
8 1 1 1   30 1.1 1.1 1.1 1.1.1
>
> #fm <- '~hp+hq+pq'
> fm <- '~h:p+h:q+p:q'
> # Both options above seem to produce the same results
>
> (mm <- as.data.frame(model.matrix(as.formula(paste0(fm, '+Freq')), pop)))
  (Intercept) Freq h0:p0 h1:p0 h0:p1 h1:p1 h0:q1 h1:q1 p1:q1
1           1   40     1     0     0     0     0     0     0
2           1   35     0     1     0     0     0     0     0
3           1   25     0     0     1     0     0     0     0
4           1   35     0     0     0     1     0     0     0
5           1   45     1     0     0     0     1     0     0
6           1   30     0     1     0     0     0     1     0
7           1   30     0     0     1     0     1     0     1
8           1   30     0     0     0     1     0     1     1
> mm <- mm * mm$Freq
    > mm$Freq <- NULL
> (pop <- unlist(lapply(mm, sum)))
(Intercept)       h0:p0       h1:p0       h0:p1       h1:p1       h0:q1
        270          85          65          55          65          75
      h1:q1       p1:q1
         60          60
>
> cal <- NULL
> cal <- calibrate(des, formula=as.formula(fm), population=pop,
+                  calfun="raking")
Loading required package: MASS
> weights(cal)
        1         2         3         4         5         6         7         8
31.902369 19.048815 16.548815 16.032544  8.967456 19.048815 16.032544 26.902369
        9        10        11        12        13        14        15
16.548815 28.097631 18.451185  8.967456  8.967456 16.032544 18.451185
attr(,"eta")
           [,1]
[1,]  2.5320998
[2,]  0.3830288
[3,]  0.4149051
[4,]  0.8035854
[5,]  0.9305805
[6,] -0.1405080
[7,]  0.3452095
[8,] -1.0015752
> svytotal(~h, cal)
   total SE
h0   140  0
h1   130  0
> svytotal(~p, cal)
   total SE
p0   150  0
p1   120  0
> svytotal(~q, cal)
   total SE
q0   135  0
q1   135  0
> svytotal(~hp, cal)
      total SE
hp0.0    85  0
hp1.0    65  0
hp0.1    55  0
hp1.1    65  0
> svytotal(~hq, cal)
      total SE
hq0.0    65  0
hq1.0    70  0
hq0.1    75  0
hq1.1    60  0
> svytotal(~pq, cal)
      total SE
pq0.0    75  0
pq1.0    60  0
pq0.1    75  0
pq1.1    60  0
> svytotal(~hpq, cal)
          total     SE
hpq0.0.0 36.902 6.4914
hpq1.0.0 38.098 6.4914
hpq0.1.0 28.098 6.4914
hpq1.1.0 31.902 6.4914
hpq0.0.1 48.098 6.4914
hpq1.0.1 26.902 6.4914
hpq0.1.1 26.902 6.4914
hpq1.1.1 33.098 6.4914

(Just for the record: The R function interaction() recodes all combinations of given factors into one single factor.)


Solving project selection with a network flow algorithm

Question: I am currently studying network flow algorithms and one of its application is supposed to be "Project Selection". A (more) complete description is given here, but the problem basically is this:
There is a graph $G$ with a number of projects $P$ as nodes. Projects have a revenue $p_i$ and a dependency from project $j$ on $i$ is given as an edge $(j,i)$.
Now it is said that the minimum cut will provide the most efficient set of projects to take if makes a source node $s$, sink node $t$ and make an edge $(s,i)$ if $p_i > 0$ and an edge $(i,t)$ if $p_i < 0$
There are however several cases I can think of that seem impossible to solve in this matter.
Consider for example a case with only 1 project ($P = {a}$) with a revenue of +10. Clearly the most profitable set of projects to do is ${a}$, but a flow is impossible in this case (and thus all possible cuts are minimal, including those without $a$).

Or if there is a project with no cost, it will not have a connection with the source nor sink and as such does not have to be in the minimum cut.
(pic coming later)
(other counter-examples I can think of basically are all based on these 2 problems)
Can anyone shed some light on this algorithm for me?
Answer: I hesitate to write this up as an answer, but I guess I don't have the 'comment' privilege yet.
These types of issues are important to understand, as they force you to understand the problem in more depth and come up with a model that accurately describes it without too much fluff.
Anytime you encounter a case that breaks your model, you can try to add something to the model that allows you to model it accurately.
The one project case is obvious: there's no problem to solve.  You either do the project or you don't.
A project with zero cost almost makes no sense.  If the cost is zero, then I'd try to change the model to more accurately describe the problem.  In the simplest case, a business choosing projects to tackle would have at least two costs in mind: time spent, money spent.
Now, suppose project X1.0 (v1.0) is already complete, but it sucks.  The choice is one of:

X1.0 -> Y1.0 (Just use it and put up with the headaches)
X1.1 -> Y1.0 (Improve X1.0)
X2.0 -> Y1.0 (Re-write it)

The cost of traversing the edge from X to Y in (1) is zero.  However, a proper model for this would have 3 nodes in the graph for Y: one for each path.  Treating Y as a single node with separate edges then creates the implicit assumption that the path from Y1.0 to Z1.0 is the same no matter which of the 3 options you pick.
In short: this is what mathematical modeling is all about.  Analyzing the problem and coming up with a good way to accurately model it.  If something breaks it, more than likely it's your model.
Answer: You misunderstood the result. Whether a flow is possible or not is not relevant.  In your first case, where the graph is
$ s \to a  \,  \ t $
the minimal cut (=partition of the nodes into two sets, one containing s and the other t) is ({s,a}, {t}) which has capacity 0 because there are no edges from one set to the other.  The other cut ({s},{a,t}) has capacity 10 (the capacity of the edge from s to a).  In the other example with revenue 0, both possible cuts have capacity 0 so you can either do project a or not; both are optimal.


Frame Drum Over-Stretch

Question: I have a Synthetic skin 20" Remo Frame Drum and it seems that I have over-tightened one side on one occasion resulting in a sort of wave in the drum.
I have tried loosening everything and starting again evenly several times, however, the side that was over-stretched still has a light wave through it that affects the sound of the whole drum.
Have I ruined skin on this instrument or is there a way I can repair this?
Thank you kindly for help & advice.
Answer: Neck on line here. It may well be ruined as it is,. If it was mine, I'd loosen the tension but still keep it sounding - not too flappy - and use a hair drier or gentle heat gun to 'brush' out the kink, tightening gently on the way. Obviously not hot enough to melt or distort the skin. I've never tried it, but it's worth a try. Worst case scenario, throw it away, which is what will probably have happened in the absence of any other solution.
Comment: If you remove the skin from the drum, will it lay flat on a table without showing the "wave"? If not, throw it away - you have permanently over-stretched it, and there is no way to reverse that.
Answer: Take the head off, rotate it 90 or 180 degrees. Then re-tension it by counting turns of the key. This should seat the head more correctly. The hair dryer trick may help and it shouldn't do any harm

Frame Drum Over-Stretch


How can I fix this query error with drush sql-sync?

Question: I crafted my drush/sites/self.site.yml like below* and verified that drush rsync @prod:%files @self:%files worked. However, drush sql-sync @prod @self results in the following error:
  The command "/usr/local/bin/drush sql-query --strict=0 --file=/tmp/termitral_db_20211011_110905.sql.gz --file-delete --uri=drupal --root=/var/www/drupalvm/drupal/web" failed.

  Exit Code: 1(General error)

  Working directory:

  Output:
  ================

  Error Output:
  ================

  In SqlCommands.php line 199:

    Query failed.

  sql:query [--result-file [RESULT-FILE]] [--file FILE] [--file-delete] [--extra EXTRA] [--db-prefix] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--database [DATABASE]] [--target [TARGET]] [--db-url DB-URL] [--notify [NOTIFY]] [--druplicon] [--xh-link XH-LINK] [--] <command> [<query>]

On closer look (aka verbose), I noticed this** and I was told on Drupal Slack that --file only takes an uncompressed SQL file (I later verified this). So my question is, how can I fix this dreadful error?
*
prod:
  host: example.com
  user: user
  root: /data/web/public_html/web
  uri: default
  paths:
   - files: sites/default/files

**
// Copy new and override existing files at
// /tmp/termitral_db_20211011_103342.sql.gz. The source is
// email@example.com:/data/web/drush-backups/termitral_db/20211011103342/
// termitral_db_20211011_103342.sql.gz?: yes.

and

The command "/usr/local/bin/drush sql-query --strict=0 --file=/tmp/termitral_db_20211011_103342.sql.gz --file-delete --uri=drupal --root=/var/www/drupalvm/drupal/web" failed.

Comment: I remember this issue from one DDEV project and the workaround was to simply check the /tmp directory, because the file gets downloaded but not imported somehow, and then gunzip and import the database from there. `ddev ssh` and there `cd /tmp`, then `ls -lhA` to get the latest database file name, and then `gunzip < test_20210928_110056.sql.gz | drush sqlc`. It's just a workaround though. And only happened in one single DDEV instance. Still not solved, yet.
Comment: Which version of Drush BTW?
Comment: Yeah, sorry. 9.7.3.
Comment: Can you confirm the workaround? That the downloaded database actually exists in the /tmp folder and just the import didn't work?
Comment: It exists in /tmp and import didn't work. It only works if I decompress it.
Comment: Just FYI: " --file=FILE. Path to a file containing the SQL to be run. Gzip files are accepted." from https://www.drush.org/latest/commands/sql_query/
Comment: And finally, this may be a workaround, https://github.com/drush-ops/drush/issues/4319#issuecomment-790558557
Answer: More information about others with the same problem (https://github.com/drush-ops/drush/issues/4319#issuecomment-790558557)

There are two ways to solve this:

Upgrade drush to v10 (better even would be 11)
(https://www.drush.org/latest/install/#drupal-compatibility)

Or, patch your current drush using something like the following:
diff --git a/includes/drush.inc b/includes/drush.inc
index a8f356ff8..85d56f617 100644
--- a/includes/drush.inc
+++ b/includes/drush.inc
@@ -352,6 +352,7 @@ function drush_file_is_tarball($path) {
   $supported = [
     'application/x-bzip2',
     'application/x-gzip',
+    'application/gzip',
     'application/x-tar',
     'application/x-zip',
     'application/zip',

Good luck!


Standardized coefficients logistic Regression R

Question: Is there an analogue to the standardized logistic regression coefficients I can get in Stata for R? I know in regression it is simply lm.beta(model). Is there something like this for logistic regression or profit?
Answer: Standardization is not a good idea.  It doesn't work for categorical variables or for continuous variables that have nonlinear effects on Y.  The standard deviation doesn't work properly when X has an asymmetric distribution.  Find a meaningful range for X and compute differences in predicted Y over that range.  Inter-quartile-range X effects are useful first attempts.  More here.
Answer: Independent of software, for logistic regression, if you mean-zero standardize any covariates using the relationship
$z_{ij}=\frac{x_{ij}-\bar{x}_j}{\sigma_j}$,
then you can recover what the coefficient, $\beta_j$, for variable $\mathbf{x}_j$ would have been, by dividing the coefficient, $\beta_j^*$, from regression based on $\mathbf{z}_j$, with the s.d. of $\mathbf{x}_j$, as in
$\beta_j = \frac{\beta_j^*}{\sigma_j}$


MSYS Installation - Silent Mode

Question: I want to install MSYS silently,(i.e.) I want to install from command line. I tried various option like
<code>C:> MSYS-1.0.11-rc-1.exe /S
C:> MSYS-1.0.11-rc-1.exe /s
C:> MSYS-1.0.11-rc-1.exe /silent
</code>
but none worked, Could anyone help me out with a solution.
-Shiva
Answer: You could instead download an all-in-one zip package of all MSYS packages from the mingw-w64 site.
If you feel this is missing updated packages, please contact me, and I'll upload a new all-in-one package.
Comment: @StevenPenny I hid the URL behind blue text. It's not like I can change the URL itself...

MSYS Installation - Silent Mode


alguem tem ideia do porquê o if não ser executado?

Question: if (strcmp(letra4, "[") == 0) {
  char string_sem_colchete[10];
  for(i=1; i<strlen(comando4)-1; i++)
  {
    string_sem_colchete[i-1] = comando4[i];
  }

  string_sem_colchete[i-1] = '\0';
  numero4 = atoi(string_sem_colchete);
  printf("%i", numero4);
}

Em resumo a variável letra4 é a primeira posição de uma string, se caso o caractere dessa posição seja "[", ele executará esse código dentro do if para retirar o primeiro e o último caractere dessa string e converter em int. O código funciona, o problema é q o IF aparenta não ser executado.
Answer: Você só quer comparar o primeiro char? strcmp compara a string inteira. Só passaria no if se sua string fosse só "[".
Compare só a primeira posição: if (letra4[0] == '[')... Isso imaginando que letra4 seja ou um vetor ou um ponteiro, pois você deixou o mistério no ar né?
Comment: isso, eu já tentei fazer isso, mas não foi tbm, aí eu armazenei o primeiro caractere de outra string no char letra4, eu printo essa variavel e aparece "[", por isso eu não tenho a miníma ideia do porque o if não ser executado
Answer: Como menciona que a variável letra4 é a primeira posição de uma string, acredito que esteja querendo comparar chars. Se for esse o caso, comparar os valores diretamente deveria ser suficiente (note que estou usando aspas simples, isso denota o tipo char e não string):
if (letra4 == '[') {
A comparação que está tentando fazer com strcmp atualmente deveria receber dois ponteiros (strings ou char*) em sua chamada. Funcionaria caso estivesse passando char* (apenas como um exemplo, lembre-se de alocar e liberar a memória usada):
char* letra4 = "[";
Utilizando ponteiros e não char, você pode fazer a comparação com strcmp.

E caso sua string seja um array de chars literal:
char letra4[20] = {/*...*/};
Pode comparar apenas a primeira posição do seu array:
if (letra4[0] == '[') {
Espero ter ajudado de alguma forma.
Comment: nossa eu não tinha ideia de que aspas simples era pra char e aspas duplas era pra strings, pra mim era tudo a mesma coisa kkkkkkkkkk

muito obrigado, vou ver se funciona aq
Comment: eu tentei usar aspas simples, tentei comparar a outra string com posições [0], [1], [2]... mas nada, aí eu tentei fazer um simples if(letra4 == '['){} e aparentemente funcionou kkkkkkkkkk
Answer: Se não está entrando no IF, acredito que 'letra4' está apresentando outro valor.
Tente colocar breakpoint e acessar o conteudo dessa variavel.
Caso tenha duvidas sobre a doc do 'strcmp':
http://linguagemc.com.br/a-biblioteca-string-h/
Comment: tipo assim, letra4 é o primeiro caractere de uma string... letra4 = comando[0], eu printo a variável letra4, e oq aparece é "[", por isso que eu não tenho ideia do porquê o if não ser executado
Comment: Nesse caso voce tem um char.... e nao um char[]... voce poderia fazer o if assim:
if (letra4 == '[' ), com aspas simples... talvez esteja ai seu problema.


one and only one double root(quartic equation)

Question: I want to know how I can determine all positive real values of $b$ for which this equation will have one and only one double root: $x^4 +8x^3 + (288-72b)x^2 + (1088-32b)x + (4b-136)^2 = 0$.
Any help appreciated. Thanks.
Answer: HINT:
If Monic Polynomial $f(x)$ has exactly one double root $a, f'(a)=0,$
$(f(x),f'(x))=x-a$
Comment: @Shobhit, if $$f(x)=(x-a)^n\cdot g(x), f'(x)=(x-a)^n\cdot g'(x)+n(x-a)^{n-1}\cdot g(x)=(x-a)^{n-1}((x-a)\cdot g'(x)+n\cdot g(x))$$ Here  $n=2$
Comment: @Shobhit, this should help  http://math.stackexchange.com/questions/140797/how-to-tell-if-a-quartic-equation-has-a-multiple-root
Comment: @Shobhit, have you read lines  "$\triangle= 0,$ at least two equal roots;" and "roots real, two and only two equal"
Answer: values satisfying the equations are 9,34.


Stopping Drupal 7 spammers registering at mysite.com

Question: I have a new Drupal 7 site at mysite.com (address changed) - a CentOS 5.5 Linux machine in my full control.
By reading registration mails (they run through my Gmail account) I've noticed, that Drupal spammers seem to refer to my site via the address forum.mysite.com. Since any requests to a subdomain.mysite.com are redirected by my hoster to mysite.com, this works for them.
I wonder, if anyone has noticed same pattern (seems to be some common spammer tool behaviour) and what have you done? I'm thinking of using mod_rewrite to block access to forum.mysite.com, but maybe there is a better way? (Because I'm not sure if that spammer tool will go away if I close access to forum.mysite.com).
I've also thought of maybe changing my httpd.conf somehow:
<code>NameVirtualHost 18.104.22.168:80

<VirtualHost 184.108.40.206:80>
    DocumentRoot /var/www/html/mysite.com

    ServerName mysite.com
    ServerAlias mysite.com *.mysite.com
</code>
I'm not asking about Mollom or Captcha modules, because they seem to be not-up-to-date for Drupal 7 yet. And the spam users aren't a too big problem for my site anyway, because it has a card game embedded at the front page and I have a cron job deleting users not playing that game.
Answer: There is Honeypot as well

Honeypot uses both the honeypot and timestamp methods of deterring
  spam bots from completing forms on your Drupal site

Usually, forms take at least a few seconds to fill out when a human is entering data into them—especially surveys, user registration forms, etc. Spam bots try to fill out as many forms as they can in as little time as possible, so they will often fill out a form within a couple seconds at most. The Honeypot module requires at least 5 seconds to pass (by default - you can adjust this too!) before a form can be submitted.
Alternative modules
There are many spam-protection modules on drupal.org, some of which have more or less robust methods of dealing with form spam. Some of the most used and recommended include:
Mollom - Offers spam protection through their premium service.
CAPTCHA - A simple image-based CAPTCHA builder.
reCAPTCHA - Implements reCAPTCHA for image-based CAPTCHAs.
Hidden CAPTCHA - Similar to this module in it's effectiveness.
Comment: Honeypot maintainer here; you can also do some more advanced things with Honeypot like Drupal.org does to make it even harder for spammers to do their work. Check out the hooks in honeypot.api.php.
Answer: If there is any kind of form involved, try this:
I have had great success by using a fake e-mail field. The field named 'e-mail' was invisible and would never be filled out by users.
The e-mail field that I actually used was named something different, e.g. e-mail2.
Spammers would fill out the field named 'e-mail', which instantly marked them as spammers. Users would never even see that field.
If there are no forms involved or you cannot do this in Drupal, you can ignore this answer. ;)
Good luck!
Comment: Thanks for your reply! I welcome any creative answer and this is one of them :-) Currently I actually have a Gender field (because I need to know user Gender for my card game anyway) and set it to Robot/Male/Female - it works similar to your suggestion - if someone enters Robot there, I delete that account after 2 days by a cron job.
Comment: Thanks for your reply, Alex! Keep in mind that people may choose robot for fun, or because they are a little strange. :) I would feel sour to be deleted for such a prank! ;)
Comment: I expect Timo's solution to work better than the Robot/Male/Female solution. If you offer three options, robots can randomly choose one, which would mean that -in theory- only one out of three bots will register as 'robot'.
Comment: This technique is called the 'honeypot' technique, and the Mollom modules utilises this as well to help determine HAM from SPAM out of the box
Comment: And the Honeypot module (http://drupal.org/project/honeypot) does this without requiring any third party interaction :)
Answer: As far as I can see, the Mollom module is ready for Drupal 7. Based on my Drupal 6 experience with Mollom, I would recommend it.
Comment: Mollom is definitely ready for D7. I would recommend this solution too.
Answer: For the registration process, I would suggest the Spambot module. It will stop bots trying to register by verifying their IP address, email address and username on Stop Forum Spam website.
You can optionally contribute to that service by automatically submitting your website's registration attempts.
No hassle for human users like captchas!
Answer: You can also use a Captcha module to stop bot spammers.
drupal 7 version is in beta, but does work.

A CAPTCHA is a challenge-response test most often placed within web forms to determine whether the user is human. The purpose of CAPTCHA is to block form submissions by spambots, which are automated scripts that post spam content everywhere they can. The CAPTCHA module provides this feature to virtually any user facing web form on a Drupal site.
Answer: My solution for now is to block access to forum.mysite.com/user/reset/.... by using mod_rewrite:
<code>    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^forum.mysite.com$
    RewriteCond %{REQUEST_URI} ^/user
    RewriteRule .* - [L,F]
</code>
I will see if it gets better with SPAM-robots in few days...
Answer: Coming to the party a bit late on this question, but here is a solution that has worked for me.
I have a local community based site. There is no reason for someone in Russia, for example, to ever access my site. Many of my spam posts originate from some other country. Analyzing my google site analytics I can see where those are, and, with geo ip location being solid enough to at least determine to overall country origin of, I can block them having access to any of the site. So far, I have never had anyone in my community tell me they were blocked or had problems with this, and the logs tell the same story.
Answer: I would also reccommend the Mollom module; it has helped reduce so much spam on my site, even though it still gets a little bit. Install Mollom Module for Drupal has a easy guide to installing Mollom.
Answer: So far my best experience has been adding a few fields to the registration form in combination with rules. I do like the geo IP approach even though we don't have a strictly locally based user base; past logs from a Wordpress hosted site shows that we don't have users from countries that a majority of SPAMMERS come from.
Answer: As a default, I include the following modules on Drupal 7 sites to prevent or drastically cut down on bogus accounts from being created, especially in cases where the client has requested new users only require a self-verification of their email (which spambots can sometimes get around):

Honeypot
Spambot
Mollom


Dismissing the keyboard in a UIScrollView

Question: Alright, I have a couple of UITextFields and UITextViews inside a UIScrollView, and I'd like to set the keyboard to disappear whenever the scrollview is touched or scrolled (except when you touch down inside the text field/view, of course).
My current attempt at doing this is replacing the UIScrollView with a subclass, and setting it to call a removeKeyboard function (defined inside the main view controller) inside the touchesBegan method. However, this only removes the keyboard for a normal touch, not when the view is simply scrolled. So, what's the best way to remove the keyboard inside a UIScrollView?
Thanks in advance for your help.
Answer: Here is the cleanest way to achieve this in iOS 7.0 and above.
scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

Or
scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

In Swift:
scrollView.keyboardDismissMode = .onDrag

Or
scrollView.keyboardDismissMode = .interactive

Comment: OnDrag means to dismiss the keyboard when you started dragging scroll view. Whereas Interactive means whenever you began touches in scroll view.
Comment: In swift, scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag; or scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive;
Comment: You can set it any time after controls/views are loaded. I'd recommend to put it in viewDidLoad and make sure that the scrollView is connected via IB. Even you can set it in IB. It's named Keyboard attribute under Scroll View section of Attribute inspector.
Comment: Interactive doesnt trigger in Swift.
Comment: can you give me the swift equivalent code? This dosent seem to work in swift.
Comment: I tried these two but didnt work. can you pls tell me where should I put these code? either in onTouchesBegan or viewDidLoad? And what is the difference between OnDrag and Interactive? Thanks for the response
Comment: interactive means keyboard Disappears when ever we touch a white space?
Comment: It's when you touch inside the scroll view.
Comment: Add added this in IB. (Although does seem to work in Simulator).
Comment: This is working for me however I am getting a warning in console: ```-[UIWindow endDisablingInterfaceAutorotationAnimated:] called on > without matching -beginDisablingInterfaceAutorotation. Ignoring.``` Has anyone else run into this?
Comment: Will it work if there's a `view` inside the `scrollView` and all the `textfields` are inside the `view`?
Comment: Yep, for sure. @iPeter
Comment: which one do you use .onDrag or .interactive?
Comment: Dismiss Interactively.
Comment: Try onDrag then. Some people complained that interactive isn't working well.
Comment: If .interactively is not working - set "Bounce Vertically" to true in IB for the UIScrollView. This is because your content view is not big enough to allow scrolling. You need scrolling in order for it to work
Comment: I found that if the Emoji keyboard is shown and you slide the emojis, this causes the keyboard to hide weirdly - any thoughts on how to fix that?
Answer: Bit late but if anyone else is searching an answer to this problem, this is how I have gone about solving it:
1) Create a tap gesture recognizer with a target callback method to dismiss your keyboard using resignFirstResponder on all your fields.
2) Add the tap gesture to the scrollview.
Here's an example:
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];

// prevents the scroll view from swallowing up the touch event of child buttons
tapGesture.cancelsTouchesInView = NO;

[pageScrollView addGestureRecognizer:tapGesture];

[tapGesture release];

...

// method to hide keyboard when user taps on a scrollview
-(void)hideKeyboard
{
    [myTextFieldInScrollView resignFirstResponder];
}

Comment: Works fine for me on UIScrollView with UITextFields and UIButtons.
Comment: Can you give me the swift equivalent code for this. Thank you
Comment: See my post below for the Swift version.
Comment: I don't understand why do we need to use TapGesture? There is an option available in storyboard itself. In Keyboard change "Do not dismiss" to "Dismiss on drag".
Answer: Although the essence is the same, I prefer less code.
Setting the keyboard to disappear when the scrollView is scrolled in Attributes inspector:

Then disappear keyboard when scrollView is tapped:

Drag a Tap Gesture Recognizer onto your scrollView

Only one line in the action —— scrollView.endEditing(true). If you are using Objective-C, [self.scrollView endEditing: YES];
Comment: Action is not required only in Keyboard "Dismiss on drag" is enough.
Answer: In Swift:
Bit late but if anyone else is searching an answer to this problem, this is how I have gone about solving it:
1) Create a tap gesture recognizer with a target callback method to dismiss your keyboard using resignFirstResponder on all your fields.
2) Add the tap gesture to the scrollview.
Here's an example:
import UIKit

class ViewController: UIViewController {

    @IBOutlet var t1: UITextField!
    @IBOutlet var t2: UITextField!
    @IBOutlet var t3: UITextField!
    @IBOutlet var t4: UITextField!

    @IBOutlet var srcScrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "hideKeyboard")

        // prevents the scroll view from swallowing up the touch event of child buttons
        tapGesture.cancelsTouchesInView = false

        srcScrollView.addGestureRecognizer(tapGesture)
    }

    func hideKeyboard() {
        t1.resignFirstResponder()
        t2.resignFirstResponder()
        t3.resignFirstResponder()
        t4.resignFirstResponder()
    }
}

Answer: Look at keyboardDismissMode property of UIScrollView.
// will hide keyboard when your text field is about to go beyond the keyboard.
vwScrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;

// will hide keyboard instantly once the scroll view started scrolling by user.
vwScrollView.keyboardDismissMode = UIScrollViewKeyboardDismissOnDrag;

// If you need to hide keyboard on tap of scroll view,consider adding a tap gesture or sub class and override touchesbegan: method.

Swift Version
vwScrollView.keyboardDismissMode = .interactive
vwScrollView.keyboardDismissMode = .onDrag

Answer: Try This
[self.selectedViewController.view endEditing:YES];

Answer: Create a extension class for hiding keyboard when touches scrollview/view anywhere
extension UIViewController {
  func hideKeyboardWhenTappedAround() {
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
  }

  @objc func dismissKeyboard() {
    view.endEditing(true)
  }
}

And call this method in viewDidLoad like
override func viewDidLoad() {
  super.viewDidLoad()
  self.hideKeyboardWhenTappedAround()
}

Answer: A bit late but if anyone else is searching an answer to this problem with Swift 3:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    view.endEditing(true)
}

Answer: When I added the gesture to a subclass of UIScrollView, I was having problems with the various gestures in my view tree interfering with each other, such as being able to click on subviews, scroll the view, and have the keyboard dismiss in all cases. I came up with this solution, which can be setup from a superclass of UIScrollView or from a UIViewController.
The DismissKeyboardTapGesture class uses ARC, works with any text fields under the view, and doesn't take over any clicks from subviews like buttons. Also takes advantage of iOS7 scrolling effect to dismiss keyboard.
Setting up from UISScrollView superclass:
    _dismissKeyboard = [[DismissKeyboardTapGesture alloc] initWithView:self];

or from UIViewController:
    _dismissKeyboard = [[DismissKeyboardTapGesture alloc] initWithView:self.view];

Here is the class:
@interface DismissKeyboardTapGesture : NSObject <UIGestureRecognizerDelegate>

@end

@implementation DismissKeyboardTapGesture

- (id)initWithView:(UIView *)view
{
    self = [super init];
    if (self) {
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        singleTap.cancelsTouchesInView = NO;
        singleTap.delegate = self;
        [view addGestureRecognizer:singleTap];

        if ([view respondsToSelector:@selector(setKeyboardDismissMode:)]) {
            // Bonus effect to dismiss keyboard by scrolling
            ((UIScrollView *)view).keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
        }
    }
    return self;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    // Don't stop any existing gestures in our view from working
    if (otherGestureRecognizer.view == gestureRecognizer.view) {
        return YES;
    }
    return NO;
}

- (void)singleTap:(UIGestureRecognizer*)gestureRecognizer
{
    // Close keyboard for any text edit views that are children of the main view
    [gestureRecognizer.view endEditing:YES];
}

@end

Answer: Try this scroll view delegate method -
link delegate in IB to scroll view and then cop this code (modify as per your need).
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
//sample code
    [challengeABallotComponent.voterNameTextField resignFirstResponder];
    [challengeABallotComponent.ballotNumberTextField resignFirstResponder];
    [locationInformation.pollingLocation resignFirstResponder];
}

This should work. You can try other delegate methods too like
   -(void)scrollViewDidScroll: (UIScrollView *)scrollView
{
//do your stuff
}

Answer: scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

Answer:     extension UIView{
    //Set tag via storyboard
    func keyboardDissmissInteractiveMode(_ tag:Int){
        if let scrollView = self.viewWithTag(tag) as? UIScrollView{
            scrollView.keyboardDismissMode = .interactive
        }
        if let tableview = self.viewWithTag(tag) as? UITableView{
            tableview.keyboardDismissMode = .interactive
        }
    }

    func keyboardDissmissOnDragMode(_ tag:Int){
        if let scrollView = self.viewWithTag(tag) as? UIScrollView{
            scrollView.keyboardDismissMode = .onDrag
        }
        if let tableview = self.viewWithTag(tag) as? UITableView{
            tableview.keyboardDismissMode = .onDrag
        }
    }

    func keyboardDissmissInteractiveMode(_ view:UIView){
        if let scrollView = view as? UIScrollView{
            scrollView.keyboardDismissMode = .interactive
        }
        if let tableview = view as? UITableView{
            tableview.keyboardDismissMode = .interactive
        }
    }

    func keyboardDissmissOnDragMode(_ view:UIView){
        if let scrollView = view as? UIScrollView{
            scrollView.keyboardDismissMode = .onDrag
        }
        if let tableview = view as? UITableView{
            tableview.keyboardDismissMode = .onDrag
        }
    }
}


Storing value changes in Django DB

Question: I am recording price history data in a Django model and would like to save the value whenever it changes vs. it's previously recorded value.
For example, if I check prices once a day I'd like the following...
Time | Price
1    | $10
2    | $10
3    | $12
4    | $15
5    | $15

to be recorded as...
Time | Price
1    | $10
3    | $12
4    | $15

Does anyone have any suggestions?
My models.py file
class PriceHistory(models.Model):
    product_id = models.ForeignKey('Product', on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    timestamp = models.DateTimeField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.product_id)

My current code that stores ALL rows to the database (for each row of a dataframe that is updated with new prices daily)
ph, created = PriceHistory.objects.update_or_create(
    product_id=row.product_id,
    defaults={
       "timestamp": timezone.now(),
       "price": row.price_current,
    }
)

Comment: Just check if the price is the same as the latest one before saving the PriceHistory object.
Answer: Did you try get_or_create? it will not create the new item if it already exists
obj, created = PriceHistory.objects.get_or_create(
    product_id=row.product_id,
    price=row.price_current,
    defaults={"timestamp": timezone.now()},
)

Comment: Thanks for your reply but if I filter for price & product then it will not record cases when the price returns to a historic value? Unless I am missing something!
Comment: What do you mean `price returns to a historic value`
Comment: In this example - [Day 1: $10; Day 2: $12; Day 3: $10]. The $10 on day 3 will not get saved

Storing value changes in Django DB


Arduino Leonardo, Wire.h throwing errors but no errors when set to Esp32

Question: I am trying to use the library https://github.com/tinovi/i2cArduino
I need to run this on the Arduino Leonardo, but while trying to run it, I get the errors:
<code>/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp: In member function 'int16_t SVCS3::getVal(byte)':
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:49:32: error: call of overloaded 'beginTransmission(uint16_t&)' is ambiguous
   _wire->beginTransmission(addr); // transmit to device
                                ^
In file included from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.h:10:0,
                 from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:5:
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:61:10: note: candidate: void TwoWire::beginTransmission(uint8_t)
     void beginTransmission(uint8_t);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:62:10: note: candidate: void TwoWire::beginTransmission(int)
     void beginTransmission(int);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp: In member function 'uint32_t SVCS3::getVal32(byte)':
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:65:32: error: call of overloaded 'beginTransmission(uint16_t&)' is ambiguous
   _wire->beginTransmission(addr); // transmit to device
                                ^
In file included from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.h:10:0,
                 from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:5:
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:61:10: note: candidate: void TwoWire::beginTransmission(uint8_t)
     void beginTransmission(uint8_t);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:62:10: note: candidate: void TwoWire::beginTransmission(int)
     void beginTransmission(int);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp: In member function 'int SVCS3::setReg8(byte, byte)':
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:83:32: error: call of overloaded 'beginTransmission(uint16_t&)' is ambiguous
   _wire->beginTransmission(addr); // transmit to device
                                ^
In file included from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.h:10:0,
                 from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:5:
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:61:10: note: candidate: void TwoWire::beginTransmission(uint8_t)
     void beginTransmission(uint8_t);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:62:10: note: candidate: void TwoWire::beginTransmission(int)
     void beginTransmission(int);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp: In member function 'int SVCS3::setReg(byte)':
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:91:32: error: call of overloaded 'beginTransmission(uint16_t&)' is ambiguous
   _wire->beginTransmission(addr); // transmit to device
                                ^
In file included from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.h:10:0,
                 from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:5:
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:61:10: note: candidate: void TwoWire::beginTransmission(uint8_t)
     void beginTransmission(uint8_t);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:62:10: note: candidate: void TwoWire::beginTransmission(int)
     void beginTransmission(int);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp: In member function 'int SVCS3::calibrationEC(int16_t)':
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:114:32: error: call of overloaded 'beginTransmission(uint16_t&)' is ambiguous
   _wire->beginTransmission(addr);
                                ^
In file included from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.h:10:0,
                 from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:5:
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:61:10: note: candidate: void TwoWire::beginTransmission(uint8_t)
     void beginTransmission(uint8_t);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:62:10: note: candidate: void TwoWire::beginTransmission(int)
     void beginTransmission(int);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp: In member function 'int SVCS3::newReading()':
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:134:32: error: call of overloaded 'beginTransmission(uint16_t&)' is ambiguous
   _wire->beginTransmission(addr); // transmit to device
                                ^
In file included from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.h:10:0,
                 from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:5:
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:61:10: note: candidate: void TwoWire::beginTransmission(uint8_t)
     void beginTransmission(uint8_t);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:62:10: note: candidate: void TwoWire::beginTransmission(int)
     void beginTransmission(int);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp: In member function 'void SVCS3::getData(float*)':
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:176:32: error: call of overloaded 'beginTransmission(uint16_t&)' is ambiguous
   _wire->beginTransmission(addr); // transmit to device
                                ^
In file included from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.h:10:0,
                 from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:5:
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:61:10: note: candidate: void TwoWire::beginTransmission(uint8_t)
     void beginTransmission(uint8_t);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:62:10: note: candidate: void TwoWire::beginTransmission(int)
     void beginTransmission(int);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp: In member function 'void SVCS3::getRaw(byte*)':
/home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:209:32: error: call of overloaded 'beginTransmission(uint16_t&)' is ambiguous
   _wire->beginTransmission(addr); // transmit to device
                                ^
In file included from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.h:10:0,
                 from /home/kevin/Arduino/libraries/i2cArduino-master/i2cArduino.cpp:5:
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:61:10: note: candidate: void TwoWire::beginTransmission(uint8_t)
     void beginTransmission(uint8_t);
          ^~~~~~~~~~~~~~~~~
/home/kevin/Downloads/arduino ide/arduino-nightly/hardware/arduino/avr/libraries/Wire/src/Wire.h:62:10: note: candidate: void TwoWire::beginTransmission(int)
     void beginTransmission(int);
          ^~~~~~~~~~~~~~~~~
exit status 1
Error compiling for board Arduino Leonardo.
</code>
Strange enough this compiles just fine for the ESP32 platform. Any ideas why Wire.h is failing for the Leonardo???
Answer: 'beginTransmission(uint16_t&)' is ambiguous
Probably both of your libraries(i2cArduino and Wire) have the same function.
First try to use a exemple only using the wire library then only the i2cArduino library.
So you can make sure the problem is the same function name.
The reason why with the ESP you can compile is probably ESP doesn't use one of the function of the libraries.
To solve you can find another library for the i2c.


Filter Report Builder to Max Date

Question: I have the data below
create table #Sales (ID INT,Amount Money, Dates Date, Product varchar(50))
insert into #Sales values
(1,12,'2023-01-03','M & S Trouser'),(2,22,'2023-01-01','Spoke'),(3,13,'2023-01-01','Peddal'),
(4,30,'2023-01-05','Mango'),(5,30,'2023-01-03','Milk'),(6,11,'2023-01-03','Wheel'),
(7,20,'2023-01-05','Tyres'),(8,24,'2023-01-03','Samsung TV'),(9,29,'2023-01-01','Clark'),
(10,13,'2023-01-03','Sardine'),(11,22,'2023-01-03','TM Lewis'),(12,27,'2023-01-03','Sonny Sound System'),
(13,14,'2023-01-01','Bulbs'),(14,11,'2023-01-05','Star Beer'),(15,30,'2023-01-03','Apple Tab'),
(16,15,'2023-01-03','Clutch'),(17,14,'2023-01-02','Asda shoes'),(18,27,'2023-01-05','Overtin')
select * from #Sales
drop table #Sales

In report builder i filtered the matrix with the properties.

when i run it i got erroe message

My expected Output looks like this

Any idea how i can resolve the issue?
Thanks
Answer: what you can do is create 2 datasets
The first one is :
create table #Sales (ID INT,Amount Money, Dates Date, Product varchar(50))
insert into #Sales values
(1,12,'2023-01-03','M & S Trouser'),(2,22,'2023-01-01','Spoke'),(3,13,'2023-01-01','Peddal'),
(4,30,'2023-01-05','Mango'),(5,30,'2023-01-03','Milk'),(6,11,'2023-01-03','Wheel'),
(7,20,'2023-01-05','Tyres'),(8,24,'2023-01-03','Samsung TV'),(9,29,'2023-01-01','Clark'),
(10,13,'2023-01-03','Sardine'),(11,22,'2023-01-03','TM Lewis'),(12,27,'2023-01-03','Sonny Sound System'),
(13,14,'2023-01-01','Bulbs'),(14,11,'2023-01-05','Star Beer'),(15,30,'2023-01-03','Apple Tab'),
(16,15,'2023-01-03','Clutch'),(17,14,'2023-01-02','Asda shoes'),(18,27,'2023-01-05','Overtin')
select * from #Sales where Dates = @date
drop table #Sales

The second one can be the same as above, but instead of select * from #Sales, you go select max(Dates) as default_date from #Sales ( and no where clause)
Now your report has a parameter of Dates. Set the default parameter for this to be default_date from your second dataset. You can hide the parameter if you do not want the user to be able to select other dates.
Answer: Harry's solution is fine and gives you more flexibility by using parameters, but if that's not required then it would be more efficient to do this in the dataset query, it will reduce the data returned to the report to only the records you need rather than all records which are then filtered by the report itself.
So just change the SELECT statement to this
SELECT * FROM #Sales WHERE [dates] = (SELECT MAX([Dates]) FROM #Sales)

Filter Report Builder to Max Date


Accordion in jQuery

Question: Hi I am working on an accordion I would like to know if there is a cleaner way of toggling the "plus" and "minus" signs. Bellow is the code and a link to a prototype.
jQuery
$(".discount-wrapper h2").on("click", function() {
    $(this).children('.plus-sign').toggle();
    $(this).parent().children(".discount-content-wrapper").toggle('slow');
    $(this).children('.minus-sign').toggle();
});

HTML

Accordion 3+-

My content is here

Accordion 3+-

My content is here

http://jsfiddle.net/
Answer: A more cleaner appraoch will be

$(".discount-wrapper h2").on("click", function() {
  $(this).children('.sign').text(function(i, t) {
    return t.trim() == '+' ? '-' : '+'
  });

  $(this).parent().children(".discount-content-wrapper").toggle('slow');
});
.discount-wrapper {
  position: relative;
  width: 100%;
  background-color: #f3f3f3;
  min-height: 28px;
  height: auto;
}
.discount-content-wrapper {
  display: none;
}

Accordion 3+

My content is here

Accordion 3+

My content is here

Another css based solution will be

$(".discount-wrapper h2").on("click", function() {
  $(this).children('i').toggleClass('sign-plus sign-minus');

  $(this).parent().children(".discount-content-wrapper").toggle('slow');
});
.discount-wrapper {
  position: relative;
  width: 100%;
  background-color: #f3f3f3;
  min-height: 28px;
  height: auto;
}
.discount-content-wrapper {
  display: none;
}
.discount-wrapper .sign-plus:after {
  content: '+'
}
.discount-wrapper .sign-minus:after {
  content: '-'
}

Accordion 3

My content is here

Accordion 3

My content is here

Answer: I would do it with 1 i-element element instead and just toggle the class.
So on default you have an i-element without a class which shows the plus-sign. Now when you click on your h2 you just toggle the class minus-sign (in which case the plus sign is overwritten).
https://jsfiddle.net/2t3uyq4k/
$(".discount-wrapper h2").on("click", function() {
    $(this).children('i').toggleClass('minus-sign');
    $(this).parent().children(".discount-content-wrapper").toggle('slow');
});

changed html:

Accordion 3

My content is here

Accordion 3

My content is here

and css:
.discount-wrapper {
    position:relative;
    width:  100%;
    background-color:#f3f3f3;
    min-height:28px;
    height: auto;
}

.discount-wrapper i:after {
    content: '+';
}

.discount-wrapper i.minus-sign:after {
    content: '-';
}

.discount-content-wrapper {
    display: none;
}

Comment: Here i have made some changes in css which remove the "jumping" while toggling (replaced margin with padding on h2 and p):
https://jsfiddle.net/dyzd85y4/

Accordion in jQuery


PHP - Se não existir conteúdo na linha não exiba

Question: Estou com um problema que não consigo resolver (não entendo muito de php) que acho ser simples.
Estou puxando um lista de produtos de um banco de dados, porém alguns produtos não tem imagem e eu gostaria que na hora do Loop ele não carregue os que tem alguma linha vazia.
Por exemplo: Caso não tenha nada na linha "imgmarca" ele não ecibe este produto na tela.
Ou melhor se em  não tiver nada não exibe o produto.
Segue código.
<?php
$query = sprintf("SELECT * FROM techloja ORDER  BY RAND(), id DESC LIMIT 12");
$dados = mysql_query($query, $con) or die(mysql_error());
$linha = mysql_fetch_assoc($dados);
$total = mysql_num_rows($dados);
if($total > 0) {
do {
?>

<div class="produto_interna"  title="<?=$linha['nome']?>" >
        <a href="<?=$linha['link']?>">

<?=$linha['nomepeq']?>

<img src="<?=$linha['img']?>"  title="<?=$linha['nome']?>" alt="<?=$linha['nome']?>" />

<img src="<?=$linha['imgmarca']?>" height="30px" /> R$ <?=$linha['valor']?>

 <?php
    }while($linha = mysql_fetch_assoc($dados));
 }
 ?>

Comment: @MarcosRegis era cool ensinares como ele deveria ter feito também ;) -- juntanto ao que o Marcos disse, era preferivel que usasses um `forEach($linhas as $linha)` mas aí terás que mudar a estrutura do código.
Comment: Adiciona um `if (!empty($linha)) {` depois do teu `do {` e assim ele só entra aí se a variavel $linha tiver conteudo
Comment: Não é uma boa prática utilizar `do { } while` da forma como usou.
Mesmo que só exista 1 único resultado, esse segundo `fetch` será executado.
Comment: Trocar esse do{}while por apenas o while. Assim você não precisa fazer essa checagem fora do laço, como está fazendo na terceira linha, e melhora a legibilidade do codigo.
Comment: Então esse jeito que fiz é o único que "sei" mas adicionando o if (!empty($linha))  ele continua exibindo.
Answer: Você pode fazer isso direto na query
SELECT * FROM techloja WHERE img IS NOT NULL ORDER  BY RAND(), id DESC LIMIT 12

Caso você salve o campo em branco em vez de NULL
SELECT * FROM techloja WHERE img != "" ORDER  BY RAND(), id DESC LIMIT 12

Ou pelo PHP usando a função empty()
Answer: Use este código caso apenas não queira exibir a imagem quando o campo estiver vazio.
<?php
$query = "SELECT * FROM techloja ORDER  BY RAND(), id DESC LIMIT 12";
$dados = mysql_query($query, $con) or die(mysql_error());
$total = mysql_num_rows($dados);
while($linha = mysql_fetch_assoc($dados) ) {?>

<div class="produto_interna"  title="<?php echo $linha['nome']?>" >
        <a href="<?php echo $linha['link']?>">

<?php echo $linha['nomepeq']?>

<?php
if (trim($linha['imgmarca']) != "") { ?>

<img src="<?php echo $linha['img']?>"  title="<?php echo $linha['nome']?>" alt="<?php echo $linha['nome']?>" />

<img src="<?php echo $linha['imgmarca']?>" height="30px" /> R$ <?php echo $linha['valor']?>

<?php } ?>

 <?php    } // fim while
 ?>

para evitar exibir o produto todo, use a dica do @Jeferson
Comment: Uma coisa que percebi agora é que seu SQL tem um `ORDER BY RAND(), id DESC` Escolhe apenas um dos dois pois, um anula o outro.
Comment: Havia esquecido de apagar isso do código...
Então esse código que passou deu certo, porém fica o espaço vazio onde ficaria o produto que não foi exibido.
Comment: Eu uso uma imagem de "SEM FOTO" para exibir um produto sem a foto.
Caso queira ocultar a linha inteira, use o SQL `SELECT * FROM techloja WHERE imgmarca IS NOT NULL AND imgmarca != "" ORDER  BY id DESC LIMIT 12`


How to get details about an error from RequestFailedException

Question: I am trying to port code that had been using Microsoft.WindowsAzure.Storage classes to use the newer classes in Azure.Data.Tables, Azure.Storage.Queues, etc.  From what I have been able to discern, the StorageException class has been replaced by RequestFailedException.  Unfortunately, there are some properties in StorageException that do not exist in RequestFailedException, making it difficult to log appropriate messages when an exception is encountered (for example: RequestId, RequestInformation, etc.).
The migration document does not address the differences between StorageException and the new RequestFailedException, or how to get error details from it.
It seems that either the new libraries are not yet mature enough for prime time, or maybe it is just because the documentation is lacking the relevant information and I can't find the appropriate methodologies for getting all of the error information from the RequestFailedException.
Does anyone know how to get more data out of the new class?  Here are some examples of what we used to do:
catch (StorageException e)
{
    operation.Telemetry.Properties.Add("AzureServiceRequestID", e.RequestInformation.ServiceRequestID);

Changing the above to use RequestFailedException is a problem because RequestInformation is not a property of RequestFailedException.
Here is another case:
catch (StorageException se)
{
    var ri = se.RequestInformation;
    if (ri.ErrorCode == "TableNotFound")
    {
        Logger.Info(
            $"{SJResult.MakeInfo(64)} {ri.HttpStatusCode} {ri.HttpStatusMessage}, Storage Service code={ri.ErrorCode} This is OK if HL7 has not yet received messages."); // 60240040
    }
    else
    {
        Logger.Error(
            $"{SJResult.MakeError(65)} HttpStatusCode: {ri.HttpStatusCode}, HttpStatusMessage: {ri.HttpStatusMessage}, Storage Service code={ri.ErrorCode}, " +
            $"Extended.ErrorCode: {ri.ExtendedErrorInformation.ErrorCode} Extended.ErrorMessage: {ri.ExtendedErrorInformation.ErrorMessage}"); // E0240041
        throw;
    }

Again, RequestInformation is not available in RequestFailedException.
How do we get access to all the detailed information (RequestInformation) about an exception from the new RequestFailedException class?
Answer: As you can see the definition of RequestFailedException Class (Azure) and constuctors in the latest version of azure sdk.
RequestFailedException(Int32, String, String, Exception)    : gives   HTTP status code ,specified error message, error code, and a reference to the inner exception .
And
RequestFailedException(Response)
Gives  error message, HTTP status code, error code obtained from the specified response.
The response in the argument represents the HTTP response from the service which has ClientRequestId as one of the properties as shown in the table which gets  client request id that was sent to server in the form of  x-ms-client-request-id headers.You can try the same while catching the error in the try-catch block.

In exception class you can give
public class RequestFailedException : Exception
{
...
    public RequestFailedException(int status, string message, string? errorCode, Exception? innerException)        : base(message , innerException) { }
}

Or use RequestFailedException(Response)  from which you can get ClientRequestId.
I've not tested it myself, but please check if below can be worked around which is taken from  the below references  or check if  something similar can give an idea.Also see if content property can be retrieved as a part of response.
try
{
  ...
      }
catch (Exception aex)
{
    foreach (var ex in aex.InnerExceptions)
    {
        if (ex is RequestFailedException except)
        {
        var innerException = excep.InnerException;
        if (innerException != null && innerException.GetType() == typeof(WebException))
        {
          WebException webEx = innerException as WebException;
          WebResponse resp = webEx.Response;
          var responseHeaders = resp.Headers;
          string requestId = responseHeaders["x-ms-request-id"];
          Console.WriteLine("Request Id: " + requestId);
            Console.WriteLine(except.InnerException.Message);
        }
        else
        {
            //  (not a RequestFailedException)
            Console.WriteLine($"{ex.Message}");
        }
    }

References:

How can I get Request ID when an exception occurs? (microsoft.com)
c# - How can you catch a RequestFailedException if making multiple
DownloadToAsync calls in parallel? - Stack Overflow
Answer: Here is my simple solution, somewhat based on kavya's answer...
catch (Exception ex)
{
    if (ex.InnerException is Azure.RequestFailedException rfex)
    {
        //let's create a custom error message so as not to expose sensitive information to the user
        var status = rfex.Status;   // ((Azure.RequestFailedException)ex.InnerException).Status;
        var errorCode = rfex.ErrorCode; // ((Azure.RequestFailedException)ex.InnerException).ErrorCode;
        string exmsg = $"Error is: {ex.Message}\nStatus: {status}\nError Code: {errorCode}";
        throw new Exception(exmsg);
    }
}


Why can I not static_cast a templated object down an inheritance tree?

Question: To be short:

Derived inherits from Base
Holder is templated to contains a pointer to anything
I can tell that an object know as Holder<Base> is a Holder<Derived>.
How can I tell my compiler?

This does not compile:
struct Base { };

struct Derived : Base { };

template <typename T>
struct Holder {
    T* point;
    int id;
};

Derived* d = new Derived();
Holder<Base> holder {d, 12};
Holder<Derived> specific( static_cast<Holder<Derived>>(holder) );

error: no matching conversion for static_cast from 'Holder<Base>' to 'Holder<Derived>'
This was a naive try for sure. But why does this not work and how should I get the specific holder I need?
Answer: Because Holder<Derived> is not derived from Holder<Base>, they are completely unrelated types that just happen to be generated from the same class template.
You can create a Holder<Derived> that contains the right value:
Holder<Derived> specific{ static_cast<Derived*>(holder.point), holder.id };

Or you could add that functionality to the Holder class template itself by adding a converting constructor that does the cast:
template <typename T>
struct Holder {
    Holder(T* pt, int id) : point(pt), id(id) { }

    template<typename U>
        Holder(const Holder& h)
        : point(static_cast<T*>(h.point)), id(h.id)
        { }

    T* point;
    int id;
};

Now your original attempt to use static_cast will work, because there is a valid conversion between them, or you can just write it as:
Holder<Derived> specific( holder );

That statement will compile as long as static_cast<Derived*>(holder.point) compiles.


How to obtain the taylor series of $\frac{1}{\cos x}$ up to the 6th order term?

Question: How to obtain the taylor series of $\frac{1}{\cos x}$ up to the 6th order term?
As far I know, we should use the taylor series of $\cos x$.
Comment: It is not appropriate to give a detailed answer unless you've given some [context](http://meta.math.stackexchange.com/a/9960).
Comment: You can try to use the infinite series product formula $$\sum a_n \sum b_n = \sum c_n$$ where $$ c_n = \sum_{k=0}^n  \binom n k a_k b_{n-k}$$
Comment: @N8tron I think you meant $c_n=\sum\limits_{k=0}^n a_kb_{n-k}$.
Comment: What have you tried? What are your thoughts on the problem? Give us some [context](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question#9960).
Comment: Try writing out the Taylor Series for $\cos(x)$. Do you know how to divide polynomials?
Comment: Also note $\frac 1 {\cos x } \cos x=1$
Comment: From $\cos x=1-x^2 u$ with $u={1\over2}-{x^2\over24}+{x^4\over720}+?x^6$ it follows that $${1\over\cos x}={1\over1-x^2u}=1+x^2 u+x^4u^2+x^6 u^3+?x^8\ .$$ Now expand $u^2$ and $u^3$ as far as is necessary to obtain all coefficients up to ${\rm coeff}[x^6]$ correctly. Everything else is collected in $?x^8$.
Comment: Nice catch saucy you are right
Answer: HINT
Let use

$\cos x = 1-\frac12 x^2 + \frac 1 {4!} x^4 - \frac 1 {6!} x^6+o(x)$

and

$(1+x)^a=1+ax+\frac12 a(a-1)x^2+\frac16 a(a-1)(a-2)x^3+o(x^3)$
Comment: That is the series for $\cosh(x)$
Comment: @robjohn Opsssss...Thanks!