text:
Q: Insertar un valor en el arreglo ¿Cómo podría agregar y borrar un valor a este arreglo (vector)?
int[] arregloConValores = { 3, 106, 77, 0, 0, 0 };

//Elementos máximo del arreglo
int elementos = 6;

//Datos guardados en el arreglo
int cantidad = 3;

A: La respuesta corta es que no se puede eliminar o agregar elementos a un vector, si somos rigurosos con las definiciones y la terminología, ya que un vector no cambia de tamaño para agregar o eliminar elementos. Es decir, un vector es siempre de tamaño fijo, como indica la propiedad IsFixedSize.
Sin embargo, puedes sustituir un elemento por otro, y como se ve en tu ejemplo, tener una variable que indique cuántos elementos significativos se ha "introducido" en el vector.
Si declaras un vector de un tamaño grande, y lo tomas como huecos que puedes rellenar con elementos, puedes en cierta manera considerar que "agregas" y "eliminas" elementos.
// Inicialización
int[] vector = new int[100];
int numeroElementos = 0;

// "Agregar" un elemento
vector[numeroElementos] = 5;
numeroElementos++;

// "Elimino" un elemento
numeroElementos--;

La clave está en que la variable numeroElementos apunta al primer "hueco" libre del vector, y al mismo tiempo nos dice cuántos elementos hemos introducido en el mismo (en realidad estamos tratando al vector como si fuera una lista).
Ahora bien, si introducimos elementos, llegará un momento en que lleguemos a llenarlo por completo, y ya no podremos agregar más elementos, porque como he dicho, no podemos re dimensionar un vector.
Lo que sí puedes hacer es crear un vector más grande, y copiar los elementos del antiguo vector al nuevo, y guardar la referencia al nuevo vector en la antigua variable. Es casi como re dimensionar el vector, pero teniendo que copiarlo, con lo que hay un gasto en tiempo y memoria añadido.
// Creamos un vector con un tamaño inicial por defecto
int vectorSize = 100;
int[] vector = new int[vectorSize];
int numeroElementos = 0;

// Si en algún momento detectamos que se llena
if (numeroElementos == vectorSize)
{
    int nuevoSize = vectorSize * 2;
    int[] copia = new int[nuevoSize];
    for (int i = 0; i < vectorSize; i++) copia[i] = vector[i];
    vector = copia;
    vectorSize = nuevoSize;
}


text:
Q: How to compare two calculated F objects I'm looking for a way to filter on a comparison of two fields calculated by models.F.
My models (simplified):
class Prescription(models.Model):
    treatment_count = models.SmallIntegerField()
    treatments_unregistered = models.SmallIntegerField(default=0)

class Treatment(models.Model):
    prescription = models.ForeignKey(Prescription)

I calculate max_treatments astreatment_count - treatments_unregistered, and I calculate actual_treatments as the number of FKs Treatment has to Prescription. Both using annotation.
Now I'd like to filter all Prescriptions where the maximum Treatments is NOT met. Basically actual_treatments < max_treatments.
I tried the below but got TypeError: 'bool' object is not iterable.

Prescription.objects.annotate(max_treatments=models.F('treatment_count')
  - models.F('treatments_unregistered')).annotate(actual_treatments=models.Count('treatment')).filter(models.F('actual_treatments')
  < models.F('max_treatments'))

I think I must be overlooking something in the documentation here or here?
If I'm not overlooking something obvious, what would be the best way to approach this?
Using Django 1.9.

A: Arguments to filter need to be in the form of Q objects or keyword arguments, rather than boolean expressions such as <. In this case, filter(actual_treatments__lt=models.F('max_treatments')).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como inserir uma data específica no Calendar do Swift3? Preciso inserir uma data específica no Calendar, porém só estou conseguindo somar valores com base na data atual (talvez porque quando instancio, dou uma Calendar.current). Alguém sabe como inserir (dia, mês e ano) separadamente?

A: Primeiro você precisa dos componentes separados utilizando DateComponents:
var dateComponents = DateComponents()
dateComponents.year = 2017
dateComponents.month = 5
dateComponents.day = 20

Daí então você pode definir uma data com base nestes componentes:
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)

Além do ano, mês e dia, existem também outros componentes que podem ser definidos.


text:
Q: Ninject register per request My ASP.NET MVC 3 application uses Ninject and Ninject ASP.NET MVC 3 integration. I have overloaded CreateKernel method.
Now I need to set some dependencies per query in this way:
if (Language == Language.English)
  //register English language implementations
else if (Language == Language.Russian)
  //register Russain language implementations

I thougt some of Request-specific methods of Global_asax would be a nice place for and tried to access some of NinjectHttpApplicaton properties to register dependencies per request. I accessed Kernel and got obsolete warning "Don't use Ninject as Service locator". What am I doing wrong? How to do it right?

A: To change the implementation based on some condition like language you should use conditional bindings. E.g. Bind<IFoo>().To<Foo>().When(ctx => Language == Language.English)


text:
Q: Huffman Coding in C with order preserving C to implement algorithms for (a) approximate order-preserving Huffman coding - each phase
merging two adjacent subtrees whose weights give the smallest sum.
The input is 1) a positive integer n and 2) a sequence of n positive integers giving the frequency
counts (weights) for symbols in an ordered character set.
Order preservation is guaranteed only when the leaf order is
consistent with the order of the character set.
I have to modify the below code to make the above possible:
    // Huffman code using a minHeap with handles (index-heap-based priority queue).
// Heap routines are adapted from "Algorithms in C, Third Edition", and
// "Algorithms in Java, Third Edition", Robert Sedgewick

// This is a prototype for demonstration purposes only.
// Minimally, the heap/priority queue implementation should
// be in a different source file.

#include <stdio.h>
#include <stdlib.h>

int N,          // Number of items in queue
        *pq,        // Priority queue
        *qp,        // Table of handles (for tracking)
        maxQueued;  // Capacity of priority queue
double *a;      // Pointer to user's table

void exch(int i, int j) {
// Swaps parent with child
    int t;

    t = pq[i];
    pq[i] = pq[j];
    pq[j] = t;
    qp[pq[i]] = i;
    qp[pq[j]] = j;
}

void PQinit(double *items, int n, int m) {
    int i;

    a = items;    // Save reference to index table
    maxQueued = m;
    N = 0;
    pq = (int*) malloc((maxQueued + 1) * sizeof(int)); // Contains subscripts to a[]
    qp = (int*) malloc(n * sizeof(int)); // Inverse of pq, allows changing priorities
    if (!pq || !qp) {
        printf("malloc failed %d\n", __LINE__);
        exit(0);
    }
// Set all handles to unused
    for (i = 0; i < n; i++)
        qp[i] = (-1);
}

int PQempty() {
    return !N;
}

int PQfull() {
    return N == maxQueued;
}

int less(int i, int j) {
// Notice how heap entries reference a[]
    return a[pq[i]] < a[pq[j]];
}

void fixUp(int *pq, int k) // AKA swim
{
    while (k > 1 && less(k, k / 2)) {
        exch(k, k / 2);
        k = k / 2;
    }
}

void fixDown(int *pq, int k, int N) // AKA sink
{
    int j;

    while (2 * k <= N) {
        j = 2 * k;
        if (j < N && less(j + 1, j))
            j++;
        if (!less(j, k))
            break;
        exch(k, j);
        k = j;
    }
}

void PQinsert(int k) {
    qp[k] = ++N;
    pq[N] = k;
    fixUp(pq, N);
}

int PQdelmin() {
    exch(1, N);
    fixDown(pq, 1, --N);
    qp[pq[N + 1]] = (-1);  // Set to unused
    return pq[N + 1];
}

void PQchange(int k) {
    fixUp(pq, qp[k]);
    fixDown(pq, qp[k], N);
}

// main implements Huffman code.
// Index is just a table of priorities whose
// subscripts are used in the PQ.

main() {
    int n, m, op, i, j, val;
    double *priority, probSum, expected = 0.0;
    int *left, *right;  // Links for Huffman code tree, root is subscript m-1
    int *parent;  // For printing the codes
    int *length;
    char *outString;

    printf("Enter alphabet size\n");
    scanf("%d", &n);
    m = 2 * n - 1;  // Number of nodes in tree
    priority = (double*) malloc(m * sizeof(double));
    left = (int*) malloc(m * sizeof(int));
    right = (int*) malloc(m * sizeof(int));
    parent = (int*) malloc(m * sizeof(int));
    outString = (char*) malloc((n + 1) * sizeof(char));
    length = (int*) malloc(m * sizeof(int));
    if (!priority || !left || !right || !parent || !outString || !length) {
        printf("malloc problem %d\n", __LINE__);
        exit(0);
    }

    PQinit(priority, m, n);

    for (i = 0; i < n; i++)
        priority[i] = (-1);

// Read and load alphabet symbols' probabilities into priority queue.
    probSum = 0.0;
    for (i = 0; i < n; i++) {
        scanf("%lf", priority + i);
        probSum += priority[i];
        PQinsert(i);
        left[i] = right[i] = (-1);
    }
    printf("Probabilities sum to %f\n", probSum);

// Huffman code tree construction
    for (i = n; i < m; i++) {
        left[i] = PQdelmin();
        right[i] = PQdelmin();
        parent[left[i]] = parent[right[i]] = i;
        priority[i] = priority[left[i]] + priority[right[i]];
        PQinsert(i);
    }
    i = PQdelmin();
    if (i != m - 1) {
        printf("The root isn't the root\n");
        exit(0);
    }
    parent[m - 1] = (-1);

// Goes breadth-first from root to compute length of prefix bit codes.
    length[m - 1] = 0;
    for (i = m - 1; i >= n; i--)
        length[left[i]] = length[right[i]] = length[i] + 1;

// Print the leaves, i.e. for the alphabet symbols
    printf("   i  prob  parent  bits product  code\n");
    for (i = 0; i < n; i++) {
        // Crawl up the tree to get prefix code
        outString[length[i]] = '\0';
        for (j = i; j != m - 1; j = parent[j])
            outString[length[j] - 1] = (left[parent[j]] == j) ? '0' : '1';
        printf("%5d %5.3f %5d %5d   %5.3f  %s\n", i, priority[i], parent[i],
                length[i], priority[i] * length[i], outString);
        expected += priority[i] * length[i];
    }
    printf("Expected bits per symbol: %f\n", expected);

// Print the internal nodes
    printf("   i  prob    left right parent\n");
    for (i = n; i < m; i++)
        printf("%5d %5.3f %5d %5d  %5d\n", i, priority[i], left[i], right[i],
                parent[i]);

    free(priority);
    free(left);
    free(right);
    free(parent);
    free(outString);
    free(length);
    free(pq);
    free(qp);
}

Following was suggested as an approach:

(a). You will want each heap entry to correspond to two adjacent
  subtrees that could be merged. After a PQdelmin() determines the merge
  to apply, you will need PQdelete() to discard unneeded candidate(s)
  (due to the merge) and a PQinsert() to include new candidate(s) (also
  resulting from the merge). Handles facilitate this.

But i am stuck for sequencing and managing the arrays.
Kindly help!

A: Due to different probabilities given to each symbol, you could have one node containing a and z, that is supposed to merge with another node containing b and c. There is no simple way of ordering non-leaf-nodes, and this gets increasingly abstract at higher levels.
Anyway; To control the order of the sub-trees, you could swap the left and right sub-trees when merging the nodes:
// Huffman code tree construction
for (i = n; i < m; i++) {
    left[i] = PQdelmin();
    right[i] = PQdelmin();
    if (CompareNodes(left[i], right[i]) > 0) {
        Swap(&left[i], &right[i]);
    }
    parent[left[i]] = parent[right[i]] = i;
    priority[i] = priority[left[i]] + priority[right[i]];
    PQinsert(i);
}

More information:

*

*Approximate Order-Preserving Huffman Code (stackoverflow)

*Order Preserving Key Compression by Antoshenkov, et. al. (pdf)


text:
Q: Google API v3: Add Event to Google Calendar Navigate to URL and giving consent:
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/calendar&state=%2Fprofile&redirect_uri=http://localhost:8080/webapp_name/calendar/calendar.html?operation=oauth2callback&response_type=code&client_id=84294424369.apps.googleusercontent.com&approval_prompt=force

I get 'code' in my method which will be used to get access token like
HttpClient client = new HttpClient();
String accessTokenURL = "https://accounts.google.com/o/oauth2/token";
PostMethod method = new PostMethod(accessTokenURL);
method.addParameter("code",request.getParameter("code"));           method.addParameter("client_id","84294424369.apps.googleusercontent.com");
method.addParameter("client_secret","sPXaCrOX_19df5iXjII7ZlCp");            method.addParameter("redirect_uri",request.getRequestURL()+"?operation=oauth2callback");
method.addParameter("grant_type","authorization_code");

int returnCode = client.executeMethod(method);

HashMap gctoken =   (HashMap)new JSONDeserializer().deserialize(method.getResponseBodyAsString());

String accessToken = gctoken.get("access_token").toString();

Now using above token to insert Event into my calendar:
String accessTokenURL = "https://www.googleapis.com/calendar/v3/calendars/jude.law@gmail.com/events";

PostMethod method = new PostMethod(accessTokenURL);
method.addParameter("access_token",accessToken);
method.addParameter("summary","New york trip");
method.addParameter("description","Chicago desc");
method.addParameter("start",(new Date()).toString());
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(Calendar.HOUR,1);
method.addParameter("end",cal.getTime().toString());

int returnCode = client.executeMethod(method);

System.out.println("Event created------->   "+method.getResponseBodyAsString());

The above code for inserting gives me error
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}

HOW to solve this Credentials problem and create entry in my google calendar?

A: Ok it is solved.
I did
HttpClient client = new HttpClient();
String accessTokenURL1 = "https://www.googleapis.com/calendar/v3/calendars/"+calId+"/events";
PostMethod method = new PostMethod(accessTokenURL1);
method.setRequestHeader("Content-Type","application/json");
method.setRequestHeader("Authorization","OAuth "+token);
method.setRequestBody(json);
int returnCode = client.executeMethod(method);


text:
Q: Is there a way to define multiple placements of a tooltip in Bootstraptour I have a custom script that I created for bootstraptour and I would like to overwrite bootstraptours original "top" placement with my own custom placement. Is there a there a way to define multiple placements of a tooltip in Bootstraptour?
The default code in bootstrap-tour-standalone.js is:
          Tooltip.DEFAULTS = {
            animation: true,
            placement: 'top', //Default
            selector: false,
            template: '

',
            container: false
          }

My custom script code is:
        'use strict';

        $(function () {
            var steps = [];
            var leadIndex = 0;
            function gensteps(index, div, message, template) {

                var id = $(div).attr('id');
                if (id === undefined) {
                    $(body).attr('id', 'id_' + leadIndex + '_' + index);
                    id = $(div).attr('id');
                }
                var step = {
                    element: '#' + id,
                    placement: 'top',
                    content: message,
                    backdropElement: '#client-activated-update-client-info'
                };
                steps.push(step);
            }

            leadIndex++;
            placement: 'left'; //I would like for this tooltip to overwrite default top placement and move to the left
            $('#Address1').each(function (index, div) {
                var template = '

 <button class="tip-skip-button">Next</button>
 <button class="tip-exit" data-role="end">Exit</button>

';
                gensteps(index, div, '
Review/Update Your Address
\n
\n
', template);
            });

            leadIndex++;
            placement: 'right'; //I would like for this tooltip to overwrite default top placement and move to the right
            $('#Address2').each(function (index, div) {
                var template = '

 <button class="tip-skip-button">Next</button>
 <button class="tip-exit" data-role="end">Exit</button>

';
                gensteps(index, div, '
Review/Update Your Address
\n
\n
', template);
            });

            var tour = new Tour({
                steps: steps
            });tour.init();tour.start(true);
            tour.goTo(0);

        });

As you can see in my first target (#Address1) I'm trying to position the  tooltip to the left and in my next target (#Address2) I would like to position the tooltip to the right but it's not working.


text:
Q: Different representation of bash in 'ps -f' command
I have two bash running; one is Terminal application that runs bash, the other one is xterm application that runs bash.
With ps -f, I have -bash one, and bash at the other.
What makes this difference?

A: I found an answer from this post: https://unix.stackexchange.com/a/46856/1090
It means that bash executed from Terminal is login-shell (-bash), when the bash from xterm is not (bash).


text:
Q: How to show $\frac{1}{2}+\frac{2}{4}+\frac{3}{8}+...+\frac{n}{2^n}<2$ using induction I´d like to show that $$\frac{1}{2}+\frac{2}{4}+\frac{3}{8}+...+\frac{n}{2^n}+\frac{n+1}{2^{n+1}}<2$$ using the fact that $$\frac{1}{2}+\frac{2}{4}+\frac{3}{8}+...+\frac{n}{2^n}<2$$
I guess the answer use transitivity of natural numbers and the inequality $$n+1<2^n$$ In this case, i can use it because i suppose it for natural n such that n>1. I'd like to have something like  $$....+(n+1)<2(2^{n+1})$$ because you can divide both sides by $2^{n+1}$, and so, you get $$...+\frac{n+1}{2^{n+1}}<2$$
I´ve noticed that $$2^n+n+1<2^n+2^n=2^{n+1}<2(2^{n+1})$$ and it leads me to think $$...+n+1<2^n+n+1$$ i´ve tried dividing both sides ,of the inequality i´m assuming as a fact, by $2^n/2$ in order to get $2^n$
in the right hand of the inequality and then, add $n+1$ to both sides: $$(\frac{1}{2}+\frac{2}{4}+\frac{3}{8}+...+\frac{n}{2^n})\frac{2^n}{2}+n+1<2(\frac{2^n}{2})+n+1=2^n+n+1$$ but at this part i get stuck because if i continue it doesn't lead me to what i´d like to show.
Please, help me. I hope someone here have already proved this before, because i don't find anything similar to this at any part of the web.

A: Hint:
$$\begin{aligned}
&\frac{1}{2}+\frac{2}{4}+\frac{3}{8}+...+\frac{n}{2^n}+\frac{n+1}{2^{n+1}}\\
=&\left(\frac{1}{2}+\frac{1}{4}+\frac{1}{8}+...+\frac{1}{2^n}+\frac{1}{2^{n+1}}\right) \\
&+\left(\frac{1}{4}+\frac{2}{8}+...+\frac{n-1}{2^n}+\frac{n}{2^{n+1}}\right)\\
\end{aligned}$$
Now try to show each bracket is less than $1$, the second bracket looks like a good candidate for the induction hypothesis.

A: In order to use induction in the way you tried, you may show a stronger inequality which implies the original one, such as
$$\frac{1}{2}+\frac{2}{4}+\frac{3}{8}+\dots+\frac{n}{2^n}\leq 2-\frac{n+a}{2^n}$$
where $a$ is a non-negative constant to be determined.
The basic step: for $n=1$ is $\frac{1}{2}\leq 2-\frac{1+a}{2}$, that is $a\leq 2$.
Then, at the inductive step, for $n\geq 1$,
$$\frac{1}{2}+\frac{2}{4}+\frac{3}{8}+\dots+\frac{n}{2^n}+\frac{n+1}{2^{n+1}}\leq \left(2-\frac{n+a}{2^n}\right)+\frac{n+1}{2^{n+1}}\stackrel{?}{\leq}2-\frac{n+1+a}{2^{n+1}}$$
and the last inequality simplifies to $a\geq 2$.
So $a=2$ works!!

A: If you can drop the method by induction you may also proceed as follows:
For $|x| < 1$ you have
 $$\frac{1}{1-x}= \sum_{n=0}^{\infty} x^n \Rightarrow \frac{1}{(1-x)^2}= \sum_{n=1}^{\infty} n \cdot x^{n-1} \Rightarrow \color{blue}{\frac{x}{(1-x)^2}= \sum_{n=1}^{\infty} n \cdot x^{n}}$$
For $x=\frac{1}{2}$ you have
$$\color{blue}{\frac{1}{2} + \frac{2}{4} + \frac{3}{8} + \cdots} = \frac{\frac{1}{2}}{\left(1-\frac{1}{2}\right)^2} \color{blue}{= 2} \Rightarrow \boxed{\sum_{n=1}^N \frac{n}{2^n}< 2} \mbox{ for all } N \in \mathbb{N}$$


text:
Q: I can't find my debug window on Android Studio I've already tried finding it by debugging a program but the debug window still doesn't open.  Also tried by activating it on view but it is greyed out. What can I do?
Here is a picture of the greyed out button.

A: Go to the View option in android studio and click on it there is a option toolbar button click on it you find the new bar will appear at the bottom in that bar you can find out the bebug window

A: Sometimes due to the cache memory Android Studio will behave in inappropriate manner. My suggestion is that go to File --> Invalidate Caches/ Restart or go to Build--> clean or Rebuild project.
If above option is for cleaning the cache memory and then  Go to --> Run-->Debug.
There you can find the debug the application.


text:
Q: SQL to get median of column from multiple tables, grouped by user id In MySQL, how would one get the median of a certain column, in my case "liked_count", aggregated across multiple tables, and group them by another column, in my case "creator_id"?
Just so I'm sure I'm being clear here; I have multiple tables with columns "liked_count" and "creator_id", I'd like to get the median liked_count for each creator across all tables, not each table individually.
I can get the average, with AVG(), but there seems to be no median function.
select a.creator_id, avg(a.liked_count) as average
from (
select creator_id, liked_count from type1
union select creator_id, liked_count from type2
union select creator_id, liked_count from type3
union select creator_id, liked_count from type4
union select creator_id, liked_count from type5
) a group by a.creator_id order by average desc, a.creator_id desc limit 10

Edit: I should add that I need the entire thing to be on the MySQL server, without returning the data to my web server, because the data sets need to scale into the millions, this function needs to be run often (and quickly (at least under 100ms, sub 50 would be better) and I need to be able to limit. As such I've added a limit to my AVG example; I need that, but for median.

A: At least as far as I know, there is no median function.
There are probably better ways to do it, but when I've needed it, I've taken the top count/2+1 items when ordered by the column in question, then taken the bottom one of that.
For my purposes that was close enough, but for a truly accurate median, you need to check if the count is even, and if so get the bottom two (the two middle items), and average their values.


text:
Q: How can we setup Cypress for IE and Edge? I need to use Cypress for testing angular and react application on Internet Explorer and Microsoft edge. I have gone through some links which mentions that Cypress supports only Chrome, Chromium and Electron. Is it true ? if not the how can i use it for testing IE and Edge.?

A: Yes it is true, currently only Chrome, Chromium and Electron are supported. You can follow https://github.com/cypress-io/cypress/issues/310 for the strategy of Cypress.io for new browser support.
So to answer the question:

how can i use it for testing IE and Edge.?

You simply can not

A: As per the documentation Canary, Chrome, Chromium and Electron are supported.
Cypress supported browsers
Which means you cannot make a test with IE or present Edge browser.
But you can try to make a test with new MS Edge Chromium. As it is using Chromium browser engine, It should work with Cypress.
The pre launched version is available to download. You can download it from link below.
Download link for new Edge Chromium

A: Cypress released Cross browser support in February 6, 2020 in their 4.0.0 update.
The list of supported browsers is now updated with a few more browsers.

A:
At the moment Cypress already supports MSEdge, but not supports IE.
You can check Cypress supported browsers

Cypress team has been working on Support for Cross Browser Testing. And currently we should have in mind two things:

*

*On February 7th, 2020 was realesed Firefox and Edge Support in Cypress 4.0 more info

*There is an active proposal for IE 11 Support, and the work required has been in someway considered. more info


text:
Q: Stuck with Simple Html Dom and extracting information I'm trying to use simple html DOM to extract everything inside a tag with the class "sitepoint". Here is my code that doesn't work:
<?php
include_once('simple_html_dom.php');

$html = file_get_html('examplewebsite');
$ret = $html->find('.sitepoint');
echo $ret;

?>

Below is an example of one of the sitepoint tags (there are ten or so) with the information inside which I want.

Get This      Now

Title

 CUT OUT SOME IMAGES AND       ADDRESSES HERE

Can anyone help me get it working?

A: You need to access the outertext attribute.
 $html->find('.sitepoint',0)->outertext;

Check the docs for more info. Look under "magic attributes"
 EDIT
When selecting classes, you need to specify which one in the document you use. I've changed the above example to reflect this. This is tested and works. (notice the 0 as the second parameter to find)


text:
Q: Critique My JavaScript Search Array Function I have been doing tons of Ajax recently and work with lots of my domain objects converted their JavaScript counterparts. I found myself writing several functions that looped through the arrays of objects to search by property values. I decided to write a simple jQuery plugin that would allow me to search an array of primitive or complex types.
Note: This is my first attempt at writing a jQuery plugin. I'm not sure if i went about it the correct way. My main concern is efficiency and cross-browser support of the search logic.
Thanks!
Code to critique:
$(function() {
    $.indexOfArray = function (search, array) {
        var keys = [];
        var index = -1;
        var primitiveType = true;
        for (var propertyName in search) {
            primitiveType = false;
            keys.push(propertyName);
        }

        if ($.isArray(array)) {
            for (var a = 0; a < array.length; a++) {
                var match = 0;
                if (primitiveType && array[a] == search) {
                    index = a;
                    break;
                }
                else if (!primitiveType) {
                    for (var b = 0; b < keys.length; b++) {
                        if (search[keys[b]] == array[a][keys[b]]) {
                            match++;
                        }
                    }
                    if (match == keys.length) {
                        index = a;
                        break;
                    }
                }

            }
        }
        return index;
    }
});

Simple example of use (It also works with primitive type arrays such as strings or ints):
var testArray = [{Id:1, FirstName: 'John'}, {Id:2, FirstName: 'Jake'}, {Id:2, FirstName: 'Jason'}];

var selectedPerson = testArray[$.indexOfArray({Id:2}, testArray)];

A: As far as cross browser goes, you don't really have anything to worry about.
In terms of efficiency, it's not bad, though you could probably do with caching some values, for examples you lookup the .length property of the arrays a lot. Also with keys[b].

A: Really nice plugin. Post it up on github while you're at it. A couple of things:
Don't call your function indexOfArray because it's not doing finding the index of a given object, but rather doing searches against keys and values given a partial/full object as a template. It also searches on primitives but that's more of an added bonus. You don't have to go with past conventions over naming this thing. Use whatever name describes it best.
You could do without declaring the keys array, and space on some space there. But that's a micro-optimization unless you're dealing with very large objects.
This may just be wishful thinking, but a search with nested object structure as search key would be really awesome :)
Nice plugin and code. Would be super useful in querying JSON documents.


text:
Q: Elasticsearch node can't connect to cluster First of all, I want to be clear that I looked at several guides and suggested similar questions before opening this post, but none of them worked for our case.
Here is our situation:
Last week, our Elasticsearch stopped adding new records as it reached the state where the disk was almost full. We changed the config to get some time and now is working as expected. However, we want to add a new server with elasticsearch and form a cluster as we don't want to resize the disk because we don't want to lose anything.
Here is the configuration for the main server /etc/elasticsearch/elasticsearch.yml
cluster.name: my-cluster
node.name: master-node
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
network.host: 0.0.0.0
http.max_content_length: 100mb
discover.seed_hosts: ["ip_address_server_1", "ip_address_server_2"]
xpack.security.enabled: true
xpack.security.transport.ssl.enabled: true
xpack.security.http.ssl.enabled: true

As I said, we created another server with the same elasticsearch version (7.6.2)
cluster.name: my-cluster
node.name: another-node
node.data: true
node.master: false
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch
network.host: ip_of_server
discover.seed_hosts: ["ip_address_server_1", "127.0.0.1"]

We tried restarting nodes at the same time, curls and everything but they can't see each other. At this point, I'm starting to think that the problem is the SSL configuration on the master, but I am not an elasticsearch expert, so I don't know what is exactly happening.
EDIT:
I took a look at the logs and here is what I found:
Node 2
[ico-elastic-node-2] master not discovered yet: have discovered [{node-2}{G5SfrEv0RxaxmYf8urIFtQ}{XpfNNouCQx2HmYfw2AvoQw}{ip_server_2}{ip_server_29300}{dil}{ml.machine_memory=12558602240, xpack.installed=true, ml.max_open_jobs=20}]; discovery will continue using [ip_server_1, 127.0.0.1:9300] from hosts providers and [] from last-known cluster state; node term 0, last-accepted version 0 in term 0

And the master:
[master-node] exception caught on transport layer [Netty4TcpChannel{localAddress=/ip:9300, remoteAddress=/ip:36660}], closing connection
io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: No available authentication scheme

Currently master is yellow. What can we try next?


text:
Q: Matrix derivative of Frobenius norm with Hadamard product inside I have to find the derivative of
$$||R - (P \circ \gamma \gamma^T)||_F^2$$ with respect to $\gamma$, where $||\cdot||_F$ is the Frobenius norm and $\circ$ is the Hadamard (elementwise) product. $R$ and $P$ are of dimension $n \times n$ and $\gamma$ of dimension $n \times r$.
I know that in general, the derivative of $||X||_F^2$ w.r.t. $X$ is $2X$, and I've tried to then use the chain rule, but I can't manage to find a coherent answer.

A: Let's define a new matrix variable
$$M=P\circ\gamma\gamma^T-R$$
And let's use a colon to denote the trace/Frobenius product, i.e.
$A:B={\rm tr}(A^TB)$.
Rules for rearranging the Frobenius product follow from the cyclic properties of the trace. Also note that the Frobenius and Hadamard products are mutually commutative
$$\eqalign{
 A:B &= B:A \cr
 A\circ B &= B\circ A \cr
 A:B\circ C &= A\circ B:C \cr\cr
}$$
Now we're ready to write down the function, differential, and gradient
$$\eqalign{
 f &= \|M\|_F^2 = M:M \cr
\cr
df &= 2M:dM = 2M:P\circ d(\gamma\gamma^T) \cr
 &= 2P\circ M:(d\gamma\,\gamma^T+\gamma\,d\gamma^T) \cr
 &= 2(P\circ M+P^T\circ M^T):d\gamma\,\gamma^T \cr
 &= 2(P\circ M+P^T\circ M^T)\gamma:d\gamma \cr
\cr
\frac{\partial f}{\partial \gamma} &= 2(P\circ M+P^T\circ M^T)\gamma \cr\cr
}$$

A: I'm working on:
$$ f \left( x \right) = \frac{1}{2} \left\| P \circ x {x}^{T} - R \right\|_{F}^{2} $$
Defining $ X = x {x}^{T} $ we can first differentiate with respect to $ X $ and then multiply by the derivative of $ X $ with respect to $ x $:
$$
\frac{d}{d {x}_{k}} f \left( x \right) = \frac{ d }{d X} \frac{1}{2} \left\| P \circ X - R \right\|_{F}^{2} \frac{d}{d {x}_{k}} X
$$
Now, the first is easy:
$$ \frac{ d }{d X} \frac{1}{2} \left\| P \circ X - R \right\|_{F}^{2} = P \circ \left( P \circ X - R \right) $$
The second is tricky but if you understand the operation it becomes:
$$ \frac{d}{d {x}_{k}} X = \sum_{i} {X}_{i, k} + \sum_{j} {X}_{k, j} $$
Hence:
$$ \frac{d}{d {x}_{k}} f \left( x \right) = \sum_{i} {P}_{i, k} \left( {P}_{i, k} {X}_{i, k} - {R}_{i, k} \right) {x}_{i} + \sum_{j} {P}_{k, j} \left( {P}_{k, j} {X}_{k, j} - {R}_{k, j} \right) {x}_{j} $$
I validated it using Finite Differences (Numerical Derivative) in MATLAB:
vX          = randn([dimOrder, 1]);
hNormFun    = @(vX) 0.5 * (norm( mP .* (vX * vX.') - mR, 'fro' ) ^ 2);

vGNumerical = CalcFunGrad(vX, hNormFun, difMode, epsVal);

mX          = vX * vX.';
vGAnalytic  = zeros([dimOrder, 1]);

for kk = 1:dimOrder
    for ii = 1:dimOrder
        vGAnalytic(kk) = vGAnalytic(kk) + mP(ii, kk) * (mP(ii, kk) .* mX(ii, kk) - mR(ii, kk)) * vX(ii);
    end
    for jj = 1:dimOrder
        vGAnalytic(kk) = vGAnalytic(kk) + mP(kk, jj) * (mP(kk, jj) .* mX(kk, jj) - mR(kk, jj)) * vX(jj);
    end
end

disp(['Maximum Deviation Between Analytic and Numerical Derivative - ', num2str( max(abs(vGNumerical - vGAnalytic)) )]);

Maximum Deviation Between Analytic and Numerical Derivative - 4.5832e-08

The full code can be found in my StackExchnage Mathematics Q2444284 GitHub Repository.


text:
Q: Does w3wp.exe keep extra crash information I have created several websites that run from ISAPI dll's, which runs smoothly in most cases. Only on one server I get events like these:
Event Type: Error
Event Source:   Application Error
Event Category: (100)
Event ID:   1000
Date:       28/04/2011
Time:       3:04:21
User:       N/A
Computer:   DIGIPROMNG
Description:
Faulting application w3wp.exe, version 6.0.3790.3959, faulting module unknown, version 0.0.0.0, fault address 0x01bdd762.

Does w3wp.exe keep extra crash information like stack dumps, or for which application pool it was running?

A: Perhaps you can find information in the log file.
 C:\inetpub\logs\LogFiles\W3SVC1

... or ...
 C:\Windows\System32\LogFiles\W3SVC1

Another possibility is to use Microsofts IIS crash tool, or if possible debug the process with Visual Studio.
IIS Debug Diagnostic Tool v1.2


text:
Q: Change of observer vs change of reference frame I read this statement "A change in observer affects the points in space-time and not the coordinates of points. However, a change of reference frame changes the coordinates of points (and not the points themselves) and is simply governed by a coordinate transformation."
Source: Nonlinear Solid Mechanics: A Continuum Approach for Engineering Science G. Holzapfel
I don't understand in what way are the points affected with the change of observer if their coordinates didn't change knowing that each observer has its own reference frame.

A: Without seeing the context from which the quoted sentence was extracted, it is hard to know what its author meant. However, I assume what they meant was as follows...
Suppose you have an observer in London recording their observations using a map centred on London. If the observer switches to using a map centred on Paris, the observer's real position doesn't change (they are still in London) and the surroundings they observe do not change- all that has changed is that the observer uses a new set of map references to label what they see. However, if the observer changes to one in Paris, the position of the observer and what they observe have changed in a real sense, regardless of whether they use a map centred on London or one centred on Paris to refer to the coordinates of their observations.


text:
Q: Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` - andriod studio I've updated my SDK version to 31, afterward I get this error. this is my Gradle :
compileSdk 31
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.cima.cima4u1"
minSdkVersion 21
targetSdk 31
versionCode 60
versionName "3.5.0"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
than i got the error :
Error:
    android:exported needs to be explicitly specified for <activity>. Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported` when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

my manifast file as the following :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.cima.cima4u1"
    tools:ignore="MissingLeanbackLauncher">

    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" tools:node="remove"/>

    <application
        android:name="com.cima.cima4u1.utils.MyAppClass"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        tools:ignore="GoogleAppIndexingWarning">

        <activity android:name="com.cima.cima4u1.RazorPayActivity" />
        <activity android:name="com.cima.cima4u1.SearchActivity" />
        <activity
            android:name="com.cima.cima4u1.PapalPaymentActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity android:name="com.cima.cima4u1.WebViewActivity" />

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="@string/admob_application_id" />
        <meta-data
            android:name="com.onesignal.NotificationOpened.DEFAULT"
            android:value="DISABLE" />
        <meta-data
            android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
            android:value="com.google.android.exoplayer2.ext.cast.DefaultCastOptionsProvider" /> <!-- facebook -->
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"
            tools:replace="android:value" /> <!-- razorpay metadata -->
        <!--
 <meta-data
            android:name="com.razorpay.ApiKey"
            android:value="rzp_live_eHkQKgddhVS9ub"/>
        -->
        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity> <!-- facebook end -->
        <activity
            android:name="com.cima.cima4u1.TermsActivity"
            android:screenOrientation="fullSensor"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.ReplyActivity"
            android:label="@string/title_activity_reply"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name="com.cima.cima4u1.ProfileActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.PassResetActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.SearchResultActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.SignUpActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.LoginActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.DetailsActivity"
            android:configChanges="screenLayout|screenSize|orientation"
            android:label="@string/title_activity_details"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan" /> <!-- android:configChanges="screenLayout|screenSize|orientation" -->
        <activity
            android:name="com.cima.cima4u1.MainActivity"
            android:theme="@style/AppTheme.Nobar"
            android:windowSoftInputMode="adjustPan" />

        <activity
            android:name="com.cima.cima4u1.SettingsActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.SplashScreenActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.cima.cima4u1.ItemMovieActivity"
            android:label="@string/title_activity_item_show"
            android:theme="@style/AppTheme.NoActionBar" />

        <activity
            android:name="com.cima.cima4u1.ItemTVActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.ItemSeriesActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.SubscriptionActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.StripePaymentActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.PurchasePlanActivity"
            android:theme="@style/AppTheme.Nobar" />
        <activity
            android:name="com.cima.cima4u1.DownloadActivity"
            android:theme="@style/AppTheme.Nobar" />

    </application>
</manifest>

i don't know honstly what i have to do to solve this one

A: Just add
android:exported="true" to your activities, like:
          <activity
            android:name="com.cima.cima4u1.TermsActivity"
            android:screenOrientation="fullSensor"
            android:theme="@style/AppTheme.Nobar"
            android:exported="true" />


text:
Q: How to access the OnClick event via Script I am trying to do a SongManager object which will be responsible for changing songs. I created a SongManager and a Song script. On runtime SongManager creates as many song buttons as i want each with different variables. Everything seems to work fine except that i cant get to OnClick event to change the songs.I tried many things but i guess its all outdated. Stuff like:
public Button.ButtonClickedEvent OnClickEvent;

or
go.GetComponent<Button>().onClick.AddListener();

Appreciate any help, thank u guys.

A: You can use Events for comminucation with your other classes. Here is the code :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class SongButton : MonoBehaviour {

    public delegate void SongButtonEvent(int index);
    public static event SongButtonEvent OnSongButtonClick;
    void ClickSongButton(){
       if (OnSongButtonClick != null)
            OnSongButtonClick (index);
    }

    public Button button;
    public Text songName;
    public int unlocked;
    public AudioClip clip;
    public int index;

    void Start () {
        button.onClick.AddListener (ClickSongButton);
    }

    public void Initialize(int index,Song song){
        this.index = index;
        songName.text = song.songName;
        unlocked = song.unlocked;
        clip = song.clip;
        button.interactable = song.isInteractable;
    }
}

First of all, i create a Initialize method. It uses Song object variables for initialization and takes an index as button id. After i create an event for notify listeners with index.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;

[System.Serializable]
public class Song
{
    public string songName;
    public int unlocked;
    public bool isInteractable;
    public AudioClip clip;
}

public class SongManager : MonoBehaviour
{

    public SongButton button;
    public Transform panel;
    public List<Song> songList;

    void OnEnable(){
        SongButton.OnSongButtonClick += SongButton_OnSongButtonClick;
    }

    void OnDisable(){
        SongButton.OnSongButtonClick -= SongButton_OnSongButtonClick;
    }

    void SongButton_OnSongButtonClick (int index)
    {
         Debug.Log ("index : " + index + " - song name : " + songList [index].songName);
    }

    void Start ()
    {
       FillList ();
    }

    void FillList ()
    {
        for (int i = 0; i < songList.Count; i++) {
            SongButton songButton = Instantiate (button) as SongButton;
            songButton.Initialize (i, songList [i]);
            songButton.transform.SetParent (panel, false);
        }
    }
}

When SongManager became enable, it starts to listen to OnSongButtonClick events. This way, you can know which button clicked.
I hope it helps.

A: You pass in the function name to the AddListener parameter.
public GameObject go;
Button myButton = null;

void Start()
{
    myButton = go.GetComponent<Button>();
    myButton.onClick.AddListener(() => myCallBackFunction());
}

void myCallBackFunction()
{
    Debug.Log("Button Clicked!");
}

You can also do: myButton.onClick.AddListener(delegate { myCallBackFunction(); });
Note:
Please post your code next time instead of posting a screenshot of it.


text:
Q: Heap dump in visualvm glassfish I have a webservice on amazon ec2 running on glassfish 4 server, I tried to connect visualvm to the server but it were impossible, so I followed this tutorial (http://looksok.wordpress.com/2012/02/10/remote-use-of-visualvm-with-xming/), I installed the plugin glassfish in the server jvisualvm, and now I can monitor glassfish, but i cant do a heap dump to see my application use of memory detailled.
How can I do?

A: You can use the jmap tool in the JDK to create an HPROF format heapdump:
http://docs.oracle.com/javase/6/docs/technotes/tools/share/jmap.html
As an example, with the PID of your GlassFish in the screenshot above, the command would be as follows:
jmap -dump:file=/path/to/my/dumpfile.hprof 1376

You could also use jps to find the process ID:
jps -v

The -v flag makes the output verbose, giving you more information to tell which process is the right one.


text:
Q: How to determine if the value is ONE-BUT-LAST in a Python generator? Since generator returns values lazily, how do I determine if the value returned from a generator is one-but-last? I spent like an hour on this and can't figure it out.
Any help appreciated. Is it even possible??
Thanks, Boda Cydo!

A: If you want to see arbitrary future values of an iterator without consuming them, you can wrap the iterator in a 'peekable' iterator, that can buffer future values.
import collections

class PeekIter(object):

    def __init__(self, iterable):
        self._iter = iter(iterable)
        self._peekbuf = collections.deque()

    def next(self):
        if self._peekbuf:
            return self._peekbuf.popleft()
        else:
            return self._iter.next()

    def peek(self, future=0, default=None):
        try:
            while len(self._peekbuf) <= future:
                self._peekbuf.append(self._iter.next())
            return self._peekbuf[future]
        except StopIteration:
            return default

Then, you can peek at future values without consuming them.
>>> p = PeekIter(range(3))
>>> p.peek()
0
>>> p.next()
0
>>> p.peek(0)
1
>>> p.peek(0)
1
>>> p.peek(1)
2
>>> p.peek(2)
>>> sentinel = object()
>>> sentinel
<object object at 0x28470>
>>> p.peek(1, sentinel)
2
>>> p.peek(2, sentinel)
<object object at 0x28470>

A: You can wrap the generator in a generator that generates a sequence of pairs whose first element is a boolean telling you whether the element is the last-but-one:
def ending(generator):
    z2 = generator.next()
    z1 = generator.next()
    for x in generator:
        yield (False, z2)
        z2, z1 = z1, x
    yield (True, z2)
    yield (False, z1)

Let's test it on a simple iterator:
>>> g = iter('abcd')
>>> g
<iterator object at 0x9925b0>

You should get:
>>> for is_last_but_one, char in ending(g):
...     if is_last_but_one:
...         print "The last but one is", char
...
The last but one is c

Too see what's happening under the hood:
>>> g = iter('abcd')
>>> for x in ending(g):
...     print x
...
(False, 'a')
(False, 'b')
(True, 'c')
(False, 'd')

A: An itertools-based solution
from itertools import tee, islice, repeat, chain, izip

def gen_with_offset(gen, offset):
    gen1, gen2 = tee(gen)
    gen2 = (False for x in gen2)
    gen2 = chain(islice(gen2, offset, None), [True], repeat(False))
    for g, sentinel in izip(gen1, gen2):
        yield g, sentinel

Usage:
>>> gex = iter('abcedefg')
>>> for p in gen_with_offset(gex, 4):
...     print p
...
('a', False)
('b', False)
('c', False)
('e', False)
('d', True)
('e', False)
('f', False)
('g', False)
>>>


text:
Q: How do IPs end up on the spam blacklists I don't know if this is the right place to ask this kind of question but here goes.
I have 3 IPs on my server,  which I'm running for shared hosting. The main shared IP gets blacklisted sometimes, obviously sometimes an account is compromised and it sends  out spam so the IP gets blacklisted, that I can understand, I try to limit it as much as I can but where I am from, it is really hard to convince a customer to update their CMS so they don't keep getting hacked.
And that goes for most accounts so no point of kicking them all really : )
The strange thing though is, I have an important account on a dedicated IP, which I thought will solve the blacklisting problem for him! To my surprise this IP address got blocked as well even though it did not send out any spam, maybe only because it is on the same subnet?? Or how do those blacklists end up blocking my other IP?
Also if you guys can point me to the right direction as to what measures I should take to prevent this from happening again and again, I thought clamd or spamassassin should work to prevent spam, but obviously they work for incoming messages not outgoing messages.
I decided to take a somewhat drastic  measure, I will setup a script that runs every hour or so, count the number of messages in the queue for each domain, and if the number exceeds X amount of messages, the domain will be blocked from sending email until reviewed.
Is there anything I can do to actually DETECT outgoing spam, so it does not have to flood the queue.
Thanks

A: Sometimes your MTA sends messages that have well known spam/viral signatures, but sometimes things are bit complicated. If some host inside your local network is infected by botnet client it can't send messages but can connect to the master host(s) of the botnet via nat/proxy. If such masterhost is ceized by antiviral service, every host that refer to it is qualified as bot host and enlisted in the BLs, even if no messages was really sended from it.
In that case you definitely can't determine what exact internal host is infected while the whole network is blacklisted. I've been trapped few times such way and still can't help with it, as far as I can't restrict anything except SMTP port.

A: The most respected blacklist (eg. spamhouse, spamcop) will blacklist an IP only if with evidence of a "bad" mail that was actualy sent by that IP, and usually will provide on their websitesome hints of the mail that triggered the blacklisting.
Other lists are more approximative and it can be difficult to detect what caused the inconvenience.
I suggest you to scan ALL the mail received by you mailserver with an antispam software AND to enforce policy limits. A good combination for postfix is spamassassin (via amavisd or similar)  + cluebringer.


text:
Q: Find unknown matrix in equation with 3 multiplications. A matrix $D$ is calculated as $A*B*C$.
I need to find the matrix $B$ given matrices $A$, $C$ and $D$.
After some trial and error it seems that the following equation is needed to reproduce matrix $B$ whilst retaining the correct order of transformations:
$B=A^{-1}*D*C^{-1}$
Why does this work?

A: Remembering that matrix multiplication is not commutative, that if $A=B$ then $AC=BC$ (it is not the case that if $A=B$, then $AC=CB$), and that $A*A^{-1}=I$, we can do the following:
$$A*B*C=D\\A*B*C*C^{-1}=D*C^{-1}\\A*B=D*C^{-1}\\A^{-1}*A*B=A^{-1}*D*C^{-1}\\B=A^{-1}*D*C^{-1}$$
Remember that this only works if matrices $A$ and $C$ are invertible.


text:
Q: Self Join Issue, incorrect syntax near 2017 I have a database with shipped quantities by month from January 2017 to present. I want to put yearly shipped numbers in unique columns by year (for the purpose of manipulating PowerBI visualziations).
The first query (without yearly columns) works:
SELECT
    FORMAT(frcst.InvDate, 'yyyyMM') AS period_name
    , MONTH(frcst.InvDate) AS month_num
    , YEAR(frcst.InvDate) AS year_num
    , frcst.LineCode
    , frcst.ClassCode
    , cc_type
    , rank
    , keycust1
    , keycust2
    , keycust3
    , sales1
    , sales2
    , sales3
    , SUM(GrossSales) AS gross_sales
    , SUM (QtyShip + ( (QtyOrd - QtyShip) * 0.25) ) AS frcst_qty
FROM
    FrcstFactTbl frcst
JOIN
    account_hierarchy_lu account ON frcst.AccountNumber = account.account_number
JOIN
    cc_type_lu cct ON frcst.ClassCode = cct.class_code
JOIN
    pop_code_lu pop ON frcst.PartNumber = pop.PartNumber
GROUP BY
    InvDate, frcst.LineCode, frcst.ClassCode, cc_type, rank,
    keycust1, keycust2, keycust3, sales1, sales2, sales3
ORDER BY
    InvDate

I am getting an error (with yearly columns) with the query:

Msg 102, Level 15, State 1, Line 12
  Incorrect syntax near '2017'

SELECT
    MONTH(frcst.InvDate) AS mnth
    , frcst.LineCode
    , frcst.ClassCode
    , cc_type
    , rank
    , keycust1
    , keycust2
    , keycust3
    , sales1
    , sales2
    , sales3
    , SUM(ship2017.GrossSales) AS 2017gross_sales
    , SUM(ship2017.QtyShip + ((ship2017.QtyOrd - ship2017.QtyShip) * 0.25)) AS 2017_frcst_qty
    , SUM(ship2018.GrossSales) AS 2018gross_sales
    , SUM(ship2018.QtyShip + ((ship2018.QtyOrd - ship2018.QtyShip) * 0.25)) AS 2018_frcst_qty
    , SUM(ship2019.GrossSales) AS 2019_gross_sales
    , SUM(ship2019.QtyShip + ((ship2019.QtyOrd - ship2019.QtyShip) * 0.25)) AS 2019_frcst_qty
    , SUM(ship2020.GrossSales) AS ship2020_gross_sales
    , SUM(ship2020.QtyShip + ((ship2020.QtyOrd - ship2017.QtyShip) * 0.25)) AS 2020_frcst_qty
FROM
    FrcstFactTbl frcst
JOIN
    account_hierarchy_lu account ON frcst.AccountNumber = account.account_number
JOIN
    cc_type_lu cct ON frcst.ClassCode = cct.class_code
JOIN
    pop_code_lu pop ON frcst.PartNumber = pop.PartNumber
JOIN
    FrcstFactTbl ship2017 ON frcst.mnth = ship2017.mnth
                          AND frcst.LineCode = ship2017.LineCode
                          AND frcst.ClassCode = ship2017.ClassCode
                          AND frcst.keycust3 = ship2017.keycust3
JOIN
    FrcstFactTbl ship2018 ON frcst.mnth = ship2018.mnth
                          AND frcst.LineCode = ship2018.LineCode
                          AND frcst.ClassCode = ship2018.ClassCode
                          AND frcst.keycust3 = ship2018.keycust3
JOIN
    FrcstFactTbl ship2019 ON frcst.mnth = ship2019.mnth
                          AND frcst.LineCode = ship2019.LineCode
                          AND frcst.ClassCode = ship2019.ClassCode
                          AND frcst.keycust3 = ship2019.keycust3
JOIN
    FrcstFactTbl ship2020 ON frcst.mnth = ship2020.mnth
                          AND frcst.LineCode = ship2020.LineCode
                          AND frcst.ClassCode = ship2020.ClassCode
                          AND frcst.keycust3 = ship2020.keycust3
WHERE
    YEAR(ship2017.InvDate) = '2017'
    AND YEAR(ship2018.InvDate) = '2018'
    AND YEAR(ship2019.InvDate) = '2019'
    AND YEAR(ship2020.InvDate) = '2020'
GROUP BY
    mnth, frcst.LineCode, frcst.ClassCode, cc_type, rank,
    keycust1, keycust2, keycust3, sales1, sales2, sales3
ORDER BY
    mnth

Any advice is appreciated.

A: First Option:
Replace 2017gross_sales, 2018gross_sales and 2019gross_sales with gross_sales_2017, gross_sales_2018 and gross_sales_2019 respectively.
It is best practice to start column names with an alpha character.
Second Option:
as per @DaleK comment you can use square bracket as well like [2017gross_sales]
Third Option:
You can use double quote " like "2017gross_sales"


text:
Q: Position charts on Django I'm trying to do something similar to this, in Django. This is part of the page of Anna:
Pos NickName      Points
--- ---------     ------
1   The best      1000
...
35  Roger         550
36  Anna          545
37  Paul          540

It's a chart showing the scoring system, and it intends to show the first position, as well as the relative position of the presented player.
Showing the first one it's easy, as it's only making a query to the database and extracting the first one:
 best = Score.objects.all().order_by('-points')[0]

But I'm having problems getting the ones close to the presented player (Anna, in this case). I don't want to go searching through the complete list, as the complete list of players can be quite long.
Maybe there's a way to know the position a register occupies in an ordered list...
Any ideas on how to achieve it?

A: Get the COUNT() of records that have a higher points.


text:
Q: Could not find 19 Android X assemblies, make sure to install nugget packages Xamarin I am trying to integrate Firebase Analytics into my app and I am following this really helpful article https://www.thewissen.io/using-firebase-analytics-in-your-xamarin-forms-app/
but when I download any of the nugget packages mentioned in the article my app gives me this error "Could not find 19 Android X assemblies, make sure to install nugget packages Xamarin".The Nugets I install are
Xamarin.FireBase.Analytics
Xamarin.FireBase.Analytics.Impl
Plugin.CurrentActivity

I follow the prompt exactly and it is asking me to install the following NUGETS:
Xamarin.androisX.Lifecycle.LiveData,
Xamarin.AndroidX.Browser,
Xamarin.Google.Android.Material,
Xamarin.AndroidX.Legacy.Support.V4

I have done that and when I clean my project and rebuild I get
java.exe exited with code 1 msb6006

I have tried removing other nugets that might be causing issues but my code only works after I remove all three of the Nugets mentioned in the article. I have read other articles and they all say to use those.
Other nuggets I have include:
Microsoft.AppCenter,
Microsoft.AppCenter.Analytics
Microsoft.AppCenter.Crashes

I don't really know how to fix this issue, I have tried reading about these packages and they all seem to be continuously worked on so they don't seem to be outdated or anything like that.
Also I followed the articles iOS implementation and it worked fine.

A: I had the same problem with adding Firebase to a new Xamarin Forms (4.8.0) app. When I updated my Android csproj file directly with the packages listed in the error message and rebuilt it worked though.


text:
Q: How to do a list with all categories and subcategories, from a given main-category I like to do a list with the name of all subcategories and sub subcategories from a giving main category.
I am really a bit new in Magento. But what I want to do, a list from all subcategories (name and url, as href) from the main category "Brands":
https://mag.outdoorequipped.com/
without the "All Brands" category but with those subcategories from "All Brands".
Any suggestions or link I can find some solution?

A: Try this.
Assume the ID of category "All Brands" is 3
    $parentCategoryId = 3;
    $childCategories = Mage::getModel('catalog/category')->getCategories($parentCategoryId);

  foreach ($childCategories as $child) {
        echo 'Name : ' . $child->getName() . '
'; // will print the sub category name
        echo 'Url : ' . $child->getRequestPath() . '

'; // will print the URL
    }

NOTE: If you want to get more info about the sub category use below lines inside above foreach() loop.
$subCatData = $child->getData();

It will get an array of sub category data.

EDIT:

If you are in the category page you can get the current category ID by using below line of code. (instead of hard-coding the category ID use this way)
$ccurrentCategoryId = Mage::getSingleton('catalog/layer')->getCurrentCategory()->getId();

So now the code would be as follows in your scenario.
 $parentCategoryId = Mage::getSingleton('catalog/layer')->getCurrentCategory()->getId();
        $childCategories = Mage::getModel('catalog/category')->getCategories($parentCategoryId);

      foreach ($childCategories as $child) {
            echo 'Name : ' . $child->getName() . '
'; // will print the sub category name
            echo 'Url : ' . $child->getRequestPath() . '

'; // will print the URL
        }

A: To get a collection of subcategories of a given category $parentCategory, use:
$subcategoryCollection = Mage::getModel('catalog/category')
    ->getCollection()
    ->addFieldToFilter('level', $parentCategory->getLevel() + 1) // remove this to go deeper
    ->addFieldToFilter('path', ['like' => $parentCategory->getData('path') . '%']);

(as described here: https://stackoverflow.com/q/5564647/664108)
As noted in the code comment above, you can use the level filter  to specify how deep you want to recurse into subcategories. To get subcategories and sub-sub-categories but not sub-sub-subcategories, use this:
->addFieldToFilter('level', ['lte' => $parentCategory->getLevel() + 2])

(lte stands for less than or equal)
If you want to show the categories sorted by parent like this
1
1.1
1.1.1
1.1.2
1.2 2
2.1

add this line:
$subcategoryCollection->setOrder('path', Varien_Data_Collection_Db::SORT_ORDER_ASC);

Depending on what data you need to display, select the attributes to select:
$subcategoryCollection->addAttributeToSelect(['name', 'description', 'image']);

You can always select all attributes with addAttributeToSelect('*') instead, but I don't recommend it because it results in unneccessary queries to the EAV tables.
Then you can foreach over $subcategoryCollection and display the subcategories however you wish.
Example template:
<?php foreach ($subcategoryCollection as $category): ?>
    <a href="<?php echo $category->getUrl() ?>">
        <?php echo $this->htmlEscape($category->getName()) ?>

<?php endforeach; ?>


text:
Q: Access Denied when Remotely Accessing SSIS SQL Server Integration Services Mystery of the Day:
I have two users who access SQL Server Integration Services remotely from their local machines.  User 1 successfully connects using the Integration Service server type in SSMS.  User 2 gets this error:

Note that 2005 is mentioned in the error, tho user 2 does not have 2005 installed.  Both User 2 and the server are running 2014.  Both users have the same persmissions on the remote server, and both are admins on the server.  User 2 also gets this error when connecting to SSIS on the server, however, she is able to connect successfully when running SSMS as an administrator on the server.  Here are some things that we've already tried:
Confirmed that User 2 is using a lower version of SQL than the version on the server.
Matched both users SSMS permissions to each other.
Added User 2 to the server's DCOM.
Restarted SSIS service on the server.
And this:

We suspect there may be a version issue between local and remote installations, but not sure what to check in that regard.  There many similar posts to our issue, but we have combed through without success.  Hoping someone can help here.
Thank you.

A: I changed the default logon of the SQL Server Integration Services 15.0 service to be the NT account on the VM I was given and was able to connect to Integration Services after a service restart.


text:
Q: Spring mvc @pathvariable sql injection Is using @PathVariable for string variable in controller safe from SQL injection attempt ?
@PathVariable("testparameter") String inputtext

A: No, it's not safe. The PathVariable annotation is just a utility to grab a token out of the URL path in a request.  In most cases this is no safer than taking a parameter from a get or post request.
Use parameterization to build your SQL queries.  That is to say, prepared statements.


text:
Q: Show images in Repeater control I have the following List:
private List<System.Web.UI.WebControls.Image> _searchResultList = new List<System.Web.UI.WebControls.Image>();

This List may contain several Images with different URLs.
I have the following Repeater:
<asp:Panel ID="SearchPanel" runat="server" ScrollBars="Vertical">
    <asp:Repeater ID="Repeater" runat="server">
        <ItemTemplate>
            <asp:Image height="32" width="32" runat="server"/>
        </ItemTemplate>
    </asp:Repeater>
</asp:Panel>

Using DataSource to display the images doesn't seem to work.
Repeater.DataSource = _searchResultList;
Repeater.DataBind();

What am I doing wrong?

A: The _searchResultList is not a list of strings so you can't use ImageURL='<%Container.DataItem.ToString()%>'. Because _searchResultList is a list of images you should bind the ImageUrl property. This should works fine for you:
<asp:Repeater ID="Repeater" runat="server">
    <ItemTemplate>
       <asp:Image ID="Image1" height="32" width="32" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' />
    </ItemTemplate>
</asp:Repeater>

In this example Container.DataItem refers to an Image control. This is why we used Eval("ImageUrl") to get the ImageUrl property of each Image control.

A:         <asp:Panel ID="SearchPanel" runat="server" crollBars="Vertical">
        <asp:Repeater ID="Repeater" runat="server">
         <ItemTemplate>
            <asp:Image height="32" width="32" runat="server" ImageURL='<%Container.DataItem.ToString()%>'/>// changes here
        </ ItemTemplate>
           </asp:Repeater>
            </asp:Panel>


text:
Q: mandatory attributes in HP ALM I have written PAF scripts and trying to sync with ALM. It throws an error like desc and expResult is missing in the activity How to resolve this?

A: All the activities associated with the flow and all tags should be updated with desc and expResult These are the mandatory attributes "desc" and "expResult".


text:
Q: Tomcat Stress Test Timeout I'm currently investigating issues on the following system:

*

*3.2 GHz 8-core machine, 24 GB ram

*Debian 6.0.2

*

*ulimit -n 4096

*ulimit -Sn 4096

*ulimit -Hn 65535

*Tomcat 6.0.28

*

*-Xmx20g

*MySQL 5.0.51a (through hibernate and a few manual JDBC queries)

*

*also pretty much room for caching

I'm testing the most common requests to the server with 2000 requests per minute remotely. Testing tool is latest jMeter. The average response time is around 65 ms, min is 35 and max is 4000ms (in rare cases, but has it's reason).
As far as I watched htop, the system specs are sufficient for at least 3 times more request per Minute. (Avg. CPU: 25%, RAM: 5 of 22GB) The server itself is accessible all the time. (Pinging it constantly while running the test.)
Important is the fact, that each request results in 3 additional requests to the local tomcat where the second finally gets the required data and the last is for statistics:
jMeter(1) -> RESTeasy-Service(2) -> ?-Service(2) -> Data-Service(2) -(new Thread)> Statistic-Service(2)
(1) is my jMeter test server and distant from (2), which is the tomcat server. Yes, the architecture might be a little weird, but that's not my fault. ^^
I switched the thread management to pool in server.xml. Set 1000 max threads up from default 200 and 10 idle up from 4. What I noticed is that the number of concurrent threads as good as never decreases, instead steadily rises up to tomcat's max it seems. htop reports 160 Threads while tomcat is stopped. About 460 when it's started freshly. (Services seem to start a few...) After a few hours (sometimes less) of hitting the server with 2000 requests per minute htop says there are 1400 tasks. This seems to be the point when I start to get timeouts in jMeter. As this is extremely time consuming I did not watch it a thousand times and therefore can't garantuee this is the cause, but that's pretty much what happens.
Primary questions:

*

*Math tells me that the concurrently used thread count should never ever exceed about 600. (34 requests * 4 requests * 4 seconds = 544, even less, but estimated 600 should be fine). As far as I understand the idea of thread pooling, unused threads should be released and stopped when idle for too long. Is there still a way I could get a thousand idling(?) threads? And is this ok?

*Could a thread started manually in one of the request processors deny the tomcat threads to be released?

*Shouldn't there be any log message telling me that tomcat could not create/fetch a thread for a request?

*Any other ideas? I'm working on this for far too long and now tomcat exhausting it's thread pool seems the only valid reason for these weird timeouts. But maybe somebody has another hint.
Thanks in advance especially if you can finally save me from this...

A: After hours and days of mind-blowing I found that the timeouts happen when Tomcat reaches it's thread limit while we're in the middle of those 3 local connection openings. I guess if it once reaches that limit one thread is waiting for another to open which will not happen while the previous do not close. In German I'd call that Teufelskreis. ^^
Whatever, solution was raise max threads to a ridiculous high number:
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="10000" minSpareThreads="10"/>
I know that this should not be the way to go, but unfortunately we all here know that our architecture is somewhat impractical and nobody got the time to change something about it.
Hope it helps somebody. =)

A: I guess, this issue needs the understanding of underlying HTTP/1.1 or HTTP/1.1 keep alive connection.
If you are using it for REST web service, probably you want to set the maxKeepAliveRequests parameter in your connector configuration to 1.
    <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           maxKeepAliveRequests="1"
           redirectPort="8443" />

This setting can be found in your $CATALINA_HOME/conf/server.xml.


text:
Q: VMWare FT, 10GbE, 4 NICs - possible? I'm trying to investigate if VMWare FT will be available in the following networking configuration.
We have 4x 10GbE NIC's, two of which are for the MPIO iSCSI networking, which leaves 2x NICs for the rest of the system.
NIC1: iSCSI MPIO
NIC2: iSCSI MPIO
NIC3: vMotion
NIC4: VM Traffic
Given that 10GbE has roughly 10x the throughput of a 1GbE networking, can FT be enabled on this configuration? I've read in the specs that they require 3x 1GbE connections (Management/vMotion, VM Traffic, FT Logging).
Can VMWare's FT features be enabled in this scenario? Or do I need to go and spec out an additional 1GbE fabric (for the Dell M1000e blade chassis)?

A: Yes, that configuration will work just fine, in fact it's quite similar to my own setup. You don't ever really need more than a single physical 1GB NIC for FT and VMotion to work - you can just put them all in one vswitch and enable those features in the management network port group.
I do have to suggest that you put the two iSCSI NICs in one vmkernel vswitch as you plan to but that you put the main vmkernel (i.e. vmotion and FT) traffic in with the VM traffic in the second vswitch and gain the benefit of having both NICs available in case of cable or port failure - the FT/vMotion traffic shouldn't be so high that it really kills the VM traffic or vice versa - if it is then I'd put in two more ports - basically you really want physical redundancy in those ports. Oh and make sure you're aware of all the limitations of FT first ok, it sounds great and works fine but I've always been able to design my way out of needing it as it has some costs.


text:
Q: Normal distribution in which 90% of samples are between 2.99 and 3.01; what is the standard deviation? Steel rods are manufactured to be 3 inches in diameter but they are acceptable if they are inside the limit 2.99 inches and 3.01 inches. It is observed that 5% are rejected as oversized and 5% are rejected undersized. Assuming that the diameters are normally distributed, find the standard deviation of the distribution.

A: First you have to transform the random variable: $Z=\frac{X-\mu}{\sigma}$
What you are looking for is $P(2.99 \leq X \leq 3.01)=2\Phi(\frac{3.01-3}{\sigma})-1=0.9$
$\Phi(.)$ is the Standard normal distribution. What you have to do next is to solve this equation for $\sigma$. The value for $\Phi(.)^{-1}$ (inverse function) can be looked up in a table.

A: Since $X$ is normally (hence symmetric with respect of its mean) distributed, the equation $P(X>3.01)=P(X<2.99)$ allows the conclusion that $\mathbb E(X)=\frac{1}{2}(3.01+2.99)=3$.
Then $X=3+\sigma U$ where $U\sim Norm(0,1)$, so that $P(U>\frac{0.01}{\sigma})=P(X>3.01)=0.05$.
This equation can be written as $1-\Phi\left(\frac{0.01}{\sigma}\right)=0.05$ where $\Phi$ denotes
the CDF of the standard normal distribution. It enables you to find $\sigma$ by means of a table.


text:
Q: Error: Not an array in Google charts I have manage to output the results from the database by outputting the following string:
[['Grupo de edad','Mujeres','Hombres'],['Menos de 40',2,0],['De 40 a 49',7,3],['De 50 a 59',8,5],['De 60 a 69',20,25],['De 70 y más',6,10]]

If i paste exactly this text into the following:
var data = google.visualization.arrayToDataTable([['Grupo de edad','Mujeres','Hombres'],['Menos de 40',2,0],['De 40 a 49',7,3],['De 50 a 59',8,5],['De 60 a 69',20,25],['De 70 y más',6,10]]);

I can visualize correctly the chart.
However, if i get the data by using jQuery .get() function and then i pass the data to google visualization function like the following:
google.load("visualization", "1.1", {packages:["corechart","bar"]});
google.setOnLoadCallback(drawVisualization);

function drawVisualization() {
    $.get("{{URL::action('ChartController@investigadoresEdadSexo')}}", function(datos, status){
        var data = google.visualization.arrayToDataTable(datos);
        var options = {
            //many options ...
        };

        var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    });//End of jQuery .get
}

I get the

Not an Array error

I know that i am passing a string, but why doesn't it work if i have tested that string by typing (copying and pasting) google.visualization.arrayToDataTable() function? Or how do i make that function interpret that string as an array?
How do i fix this?

A: Try to convert datos to an array using JSON.parse:
var data = google.visualization.arrayToDataTable(JSON.parse(datos));

UPDATE
Before parsing datos quotes ' should be transformed to ":
datos = datos.replace(/'/g, '"');
var data = google.visualization.arrayToDataTable(JSON.parse(datos));

A: When you're pasting your first text right into the function you are not pasting text, you're creating an Array element which is used by the arrayToDataTable function.
As @phts pointed out, you must parse your string to create an Array element from it. Set the dataType parameter to "json" and it'll get a JSON object as result.

A: Thank you so so much phts!!! I was getting really weird lines before the code also when generating the arraylist using jsp...
If anybody's having issues with their jsp code this is how I did it.
Connection con = (Connection) session.getAttribute("conexao");
Locale.setDefault(Locale.GERMAN);
if (con == null) {
    response.sendRedirect("fimsessao.html");
    return;
}
request.setCharacterEncoding("UTF-8");
Statement st;
ResultSet rs;
String cod = String.valueOf(session.getAttribute("cod"));

//Variáveis de Insert e Update
SimpleDateFormat dt = new SimpleDateFormat("yyyy/MM");
String dates = null;
double peso = 0;
ArrayList relPeso = new ArrayList();
relPeso.add("['Datas'");
relPeso.add("'Peso']");
try {

    String query = "SELECT `data`, `peso` FROM asaacademia.tblavaliacaofis WHERE idUsuario = '" + cod + "';";
    PreparedStatement pstm = con.prepareStatement(query);
    rs = pstm.executeQuery();
    while (rs.next()) {
        dates = dt.format(rs.getTimestamp(1));
        peso = rs.getDouble(2);
        relPeso.add("['" + dates + "'");
        relPeso.add(String.valueOf(peso) + "]");
    }

    out.print(relPeso);
    System.out.print(relPeso);

} catch (Exception e) {
    e.printStackTrace();
}

Also used this instead jQuery.parseJSON(queryObject) as per:

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.

Source: http://api.jquery.com/jquery.parsejson/
And here is my HTML code:

Peso


text:
Q: calling a function in multiple derived classes in c# How can I call a function in all derived classes when a global game state changes?
public abstract class GameStateBehaviour {

    public event EventHandler<GameStateEvents> StateChanged;

    protected virtual void OnStateChanged(GameStateEvents e) {
        // Call this function in all derived
    }

}

A: If you want to inform other classes about a state change, us use the 'observer pattern' (See: http://en.wikipedia.org/wiki/Observer_pattern). There are two parties:

*

*One party is "the object", which will change state. He has the duty to inform the others.

*The other party is "the observer". Multiple observers want to observe the state change of the object. So they want to be informed.

Try this:
class TheObject
{
    public event EventHandler<GameStateEvents> StateChanged;

    // If your object changes state, this function should be called. It informs all observers by invoking the StateChanged delegate.
    protected virtual void OnStateChanged(GameStateEvents e)
    {
        if (StateChanged != null)
            StateChanged(this, e);
    }
}

class TheObserver
{
     public TheObserver(TheObject o)
     {
         o.StateChanged += Object_StateChanged;
     }

     // This function is called by the object when the object changes state.
     private void Object_StateChanged(object sender, GameStateEvents e)
     {
     }
}

A: The OnStateChanged method is the method that should trigger the StateChanged event. Not the method that will handle this event. That is why I have added the FunctionCalledWhenStateChanges method.
public abstract class GameStateBehaviour
{
    public event EventHandler<GameStateEvents> StateChanged;

    protected GameStateBehaviour()
    {
        StateChanged += (sender, events) => FunctionCalledWhenStateChanges();
    }

    public virtual void FunctionCalledWhenStateChanges()
    {
        // The called function
    }

    protected void OnStateChanged(GameStateEvents e)
    {
        if (StateChanged != null) StateChanged(this, e);
    }
}

The solution above handles your own event. I think it is even better to implement the Template Method Pattern instead of responding to your own event. However I think you are not sure where to throw the event.


text:
Q: Why does my Dell laptop touchpad stop physically clicking when I'm at altitude? I have a Dell XPS 9560 - the touchpad will physically click when the bottom edge is depressed, except when my laptop is at high-altitude[1] the touchpad physically stops clicking and pressing down on the bottom edge doesn't have any tactile response and I have to press down so hard it hurts my fingers before the OS detects a click action (I have "tap to click" disabled, so it's only "click-to-click").
I verified it's independent of the laptop's attitude or orientation (as inside
 an aircraft cabinet in-flight the cabin is angled upwards) - so I assume that maybe the physical clicker is not using a spring or microswitch, but instead using something like an air-bubble under a membrane like cheap keyboard switches - except surely if the air pressure is lower, then the trapped air-bubble would be bigger?
(I know there are reports of the laptop battery swelling/expanding which causes the touchpad to pop-up - but the touchpad looks and feels normal and there's no sign of battery swelling - and the touchpad becomes clickable once I get to a lower altitude).
[1] e.g. atop a mountain, driving through a mountain pass, on an aircraft when the cabin is pressurized (as cabins aren't pressurized to ground-level pressure, but something like 11,000ft pressure)

A: It turns out it was the battery swelling. Dell did a warranty replacement of the battery and it's been fine ever since.


text:
Q: QT regularExpressions retrieve numbers I've to split simple QStrings of the form  "number number number",for example " 2323 432 1223".
The code i use is
QString line;
QRegularExpression re("(\\d+)");
QRegularExpressionMatch match;

while(!qtextstream.atEnd()){
     line = qtextstream.readLine();
     match = re.match(line);
     std::cout<<"1= "<<match.captured(0).toUtf8().constData()<<std::endl;
     std::cout<<"2= "<<match.captured(1).toUtf8().constData()<<std::endl;
     std::cout<<"3= "<<match.captured(2).toUtf8().constData()<<std::endl;
}

if the first line being processed is like the example string i get
for the first while cycle output:
1= 2323
2= 2323
3=
what is wrong?

A: Your regex only matches 1 or more digits once with re.match. The first two values are Group 0 (the whole match) and Group 1 value (the value captured with a capturing group #1). Since there is no second capturing group in your pattern, match.captured(2) is empty.
You must use QRegularExpressionMatchIterator to get all matches from the current string:
QRegularExpressionMatchIterator i = re.globalMatch(line);
while (i.hasNext()) {
    qDebug() << i.next().captured(1); // or i.next().captured(0) to see the whole match
}

Note that (\\d+) contains an unnecessary capturing group, since the whole match can be accessed, too. So, you may use re("\\d+") and then get the whole match with i.next().captured(0).

A: If the usage of regular expressions isn't mandatory, you could also use QString's split()-function.
QString str("2323 432 1223");
QStringList list = str.split(" ");
for(int i = 0; i < list.length(); i++){
    qDebug() << list.at(i);
}


text:
Q: Related unicode characters are displayed in different sizes or appear misaligned on OS X I am using a CMS. The special characters ◁(◁) and ▷(▷) do look far smaller on a Mac than on a Windows system (both Firefox).
△(△) and ▽(▽) looks fine though.

I already changed the font-family because I thought the reason could be problem with the font, but even using Helvetica, Western or even Tahoma and Arial those characters are small.
This looks to me like a very special Mac OS or Firefox thing.
Does anyone have an idea why that is so and what can be done?

A: The glyphs are just taken from different fonts. Like ◁ could be from Lucida Grande and ▷, △, and ▽ from Hiragino Kaku Gothic ProN.
None of the bundled versions of Helvetica, Arial, or Tahoma have any of those glyphs. Some fonts that have all of them are Arial Unicode MS, DejaVu Sans, and Lucida Sans Unicode.
It's the same problem as with sparklines like ▁▂▃▄▅▆▇█. Sometimes the full height or half height glyphs are taken from a different font, so they look misaligned.


text:
Q: calculating count of non zero values in row in dataframe I am trying to calculate count on non zero elements in row in dat frame but not working.
condition: just want to exclude one column while calculating count of non zero elements in row
i just want to select T_1_1,T_1_2,T_1_3.....and exclude T_1_0 and create a new column and check how many non zero elements available in row. what i am doing wrog here ..??
df <- data.frame("T_1_1"= c(68,24,0,105,58,0,135,126,24),
                 "T_1_2"=c(26,105,0,73,39,97,46,108,0),
                 "T_1_3"=c(93,32,73,103,149,0,147,113,139),
                 "S_2_1"=c(69,67,94,0,77,136,137,92,73),
                 "S_2_2"=c(87,67,47,120,85,122,0,96,79),
                 "S_2_3"= c(150,0,132,121,29,78,109,40,0),
                 "T_1_0"= c(79,0,0,115,98,12,15,121,2)

)

df <- df %>% select(matches("^T_1_1"),-"T_1_0") %>% mutate(new1 = rowSums(matches("^T_1_1")!=0))

A: You can use the regex 'T_1_[1-9]' to exclude T_1_0.
library(dplyr)
df <- df %>% mutate(new1 = rowSums(select(., matches('T_1_[1-9]')) !=0))
df
#  T_1_1 T_1_2 T_1_3 S_2_1 S_2_2 S_2_3 T_1_0 new1
#1    68    26    93    69    87   150    79    3
#2    24   105    32    67    67     0     0    3
#3     0     0    73    94    47   132     0    1
#4   105    73   103     0   120   121   115    3
#5    58    39   149    77    85    29    98    3
#6     0    97     0   136   122    78    12    1
#7   135    46   147   137     0   109    15    3
#8   126   108   113    92    96    40   121    3
#9    24     0   139    73    79     0     2    2

Or more specific :
df <- df %>% mutate(new1 = rowSums(select(., starts_with('T_1'), -T_1_0) !=0))

A: This also can be a solution for your problem:
library(purrr)

df %>%
  mutate(exclu_T_1_0 = pmap(df %>% select(starts_with("T_1") & !ends_with("0")),
                            ~ sum(c(...) != 0)))

  T_1_1 T_1_2 T_1_3 S_2_1 S_2_2 S_2_3 T_1_0 exclu_T_1_0
1    68    26    93    69    87   150    79           3
2    24   105    32    67    67     0     0           3
3     0     0    73    94    47   132     0           1
4   105    73   103     0   120   121   115           3
5    58    39   149    77    85    29    98           3
6     0    97     0   136   122    78    12           1
7   135    46   147   137     0   109    15           3
8   126   108   113    92    96    40   121           3
9    24     0   139    73    79     0     2           2


text:
Q: accessing to element id attribute value inside jquery.each I'm selecting html elements
var elements = $('*[my-elem="false"]');

since each element has attribute id with some value I want inside iteration to get id of currently iterated element, so I tried
$.each(elements, function(index, item){
    var itemId = item.attr("id").val();
});

but I'm getting following error
TypeError: item.attr is not a function

A: Try console.log(item). You should see that it's a regular HTML element -- not a jQuery object.
Note that .val() refers specifically to the value attribute of an element.
Both of those in mind, if your goal is to get the ID, you can use item.id, this.id, or $(item).attr("id").

A: .attr is a jQuery method, so you need to use your element as if it were a jQuery selector. Also, you don't need .val for .attr('id'), so this should work
var itemId = $(item).attr("id");

A: it is as simple as
var itemId = item.id;

A: item is a DOM element, attr is a jQuery function, so you just have to wrap it in the jQuery notation var itemId = $(item).attr('id').val();

A: You are using the wrong version of each when looping over DOM elements. Use this one. (https://api.jquery.com/each/)
elements.each(function(index){
  var itemId = $(this).attr('id').val();
});

A: Try
var elements = $('selector');
elements.each(function() {
    alert($(this).attr('id'));
});

A: var itemId = this.id;

will also work


text:
Q: Node.js Sequelize: Error in migration with foreign key I have an existing SQL Server database where I have to create a new table.
Existing Image table has column as shown in image:

I'm creating a new table using migration with a column referencing to this Image table.
My Query is
module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('NewTable', {
      IdNewTable: {
        primaryKey: true,
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false
      },
      IdImage: {
        type: Sequelize.UUID,
        references: {
          model: 'Image',
          key: 'IdImage',
        },
      }
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('NewTable');
  }
};

While running a migration, I'm getting this error

ERROR: Could not create constraint or index. See previous errors.

Can someone please help me in this?

A: I was using the wrong datatype
It should be
type: 'UNIQUEIDENTIFIER',
defaultValue: Sequelize.UUIDV4,
primaryKey: true,
allowNull: false,


text:
Q: Hierarchical Storage and Query I am editing and providing new info to this question because i've found what I need, just have a couple of questions about efficiency.
Now, I have this table:
category
--------------------------
category_id   name         parent
1           Phillips       (null)
2           Barnes          1
3           Moore           2
4           de Mohrenschildt   3
5           Oswald          9
6           Hunt            2
7           Burnham         6
8           Buckley         7
9           Paine           4
10          Sturgis         6
11          Hunt            3

I have this query:
SELECT
  t1.name AS lev1,
  t2.name AS lev2,
  t3.name AS lev3,
  t4.name AS lev4,
  t5.name AS lev5,
  t6.name AS lev6
FROM category t1
  LEFT JOIN category t2
    ON t2.parent = t1.category_id
  LEFT JOIN category t3
    ON t3.parent = t2.category_id
  LEFT JOIN category t4
    ON t4.parent = t3.category_id
  LEFT JOIN category t5
    ON t5.parent = t4.category_id
  LEFT JOIN category t6
    ON t6.parent = t5.category_id
WHERE t1.name = 'Phillips'
ORDER BY lev2

that returns:
lev1        lev2    lev3    lev4         lev5      lev6
Phillips    Barnes  Hunt    Sturgis      (null)    (null)
Phillips    Barnes  Moore   de Mohr'ldt  Paine     Oswald
Phillips    Barnes  Hunt    Burnham      Buckley   (null)

and, for a new "node":
SELECT
  t1.name AS lev1,
  t2.name AS lev2,
  t3.name AS lev3,
  t4.name AS lev4,
  t5.name AS lev5,
  t6.name AS lev6
FROM category t1
  LEFT JOIN category t2
    ON t2.parent = t1.category_id
  LEFT JOIN category t3
    ON t3.parent = t2.category_id
  LEFT JOIN category t4
    ON t4.parent = t3.category_id
  LEFT JOIN category t5
    ON t5.parent = t4.category_id
  LEFT JOIN category t6
    ON t6.parent = t5.category_id
WHERE t1.name = 'Moore'
ORDER BY lev2;

which returns
lev1    lev2        lev3    lev4    lev5    lev6
Moore   Hunt        (null)  (null)  (null)  (null)
Moore   de Mohr'dt  Paine   Oswald  (null)  (null)

Which, as you can see, is awfully close to this, in form, with some html:

*

*Phillips supervised:

*

*Barnes supervised:

*

*Moore supervised

*

*de Mohrenschildt knew:

*

*Oswald ...

*Sturgis knew

*

*Hunt knew

*

*Moore worked for...

And can hopefully mature into this one day (what's below the tabs in the image)...:

I have a couple of questions about this table and query.
1) as can be seen in the name "Hunt", the problem I may have is that when someone is assigned to more than one parent, I'm going to have to enter a new record for him. And as there are going to be, I'm guessing 5 or 600 unique persons, to repeat many of them seems to me to be unnecessary. Can someone see a better way to handle this issue, or is it even an issue? I just don't like redundancy...
2) along these lines, if you look at the image, you'll see that some of the names are in RED, denoting an AJAX dropdown paragraph of pertinent information regarding that immediate relationship. So "Hunt" may have a paragraph or two under this particular branch, and another on another branch somewhere else. I'm thinking maybe the need to repeat "Hunt" wherever necessary in the table would allow for calling another set of data to fill the AJAX dropdown. Am I asking for trouble with what I have here so far...?
3) since there will be so many branches starting with different names, is this query efficient enough if I have to run the query perhaps 40 or 50 times on one, (of many) pages, especially if it's calling some extra data as mentioned above?
I like this "schema," if that's the right word, because it seems to be really extensible. This database has the potential to grow indefinitely.
I really appreciate anyone's help with this. I'm so happy I've finally found something that's working for me (I never even knew what an Hierarchical DB is until last night, and that that's what I was looking for...)

A: Since the depth is variable and an item can have multiple parents, I recommend a general "relationship", not a parent-child hierarchy.
See this for the optimal way to write a many-to-many table.
Then you need to write multiple queries, not a single, fixed-depth, query.  There is no "good" way to traverse a tree/DAG/web (until 8.0, with CTEs).  And the speed of multiple queries, with suitable indexes and suitable caching, should be quite adequate.


text:
Q: last 10 digits of sum in given series Input contains an integer N
the series looks like this

This is a problem from hackerrank my code passed all test cases except one it is timeout actually help is appreciated
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
 public class Solution {
     public static BigInteger calculateSelfPowers(){
         Scanner z = new Scanner(System.in);
         int num = z.nextInt();
         BigInteger modval = BigInteger.valueOf(10).pow(10);
         BigInteger sum = BigInteger.ZERO;
         for (int i = 1; i <= num; i++)
         sum = sum.add(BigInteger.valueOf(i).modPow(BigInteger.valueOf(i), modval)).mod(modval);
         return sum;
     }
     public static void main(String[] args){
         System.out.println(calculateSelfPowers());
     }

 }

here is link for problem in hackerrank linkhere

A: You can improve your code by taking mod() out of the loop and by calling BigInteger.valueOf(i) only once. Addition is cheap (fast), while mod() isn't. The final sum is probably 16 or 17 digits, but you can mod() that once to get the same result as the constant reduction by mod() in your code.
This simple example (I removed the scanner and took the highest number allowed, 999999) runs in only 4 seconds on my system:
package modpowtest;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;

public class ModPowTest
{
    public static BigInteger calculateSelfPowers()
    {
        int num = 999999;
        BigInteger modval = BigInteger.valueOf(10).pow(10);
        BigInteger sum = BigInteger.ZERO;
        for (int i = 1; i <= num; i++)
        {
            BigInteger bi = BigInteger.valueOf(i);
            sum = sum.add(bi.modPow(bi, modval));
        }
        return sum.mod(modval);
    }

    public static void main(String[] args)
    {
        System.out.println(calculateSelfPowers());
    }

}

You just have to add the Scanner stuff again and rename to Solution.
If I use num = 10;, I get the same solution as they do.


text:
Q: rails updated_at not including time in one module i have the fields updated_at and created_at
but in specific module the updated_at update with no time include
I add this fields by add the  t.timestamps on create the table
while checking the query i notice that the insert update query not included the time
for example this is the output query
INSERT INTO `logs` (`admin_id`, `admin_mail`, `admin_name`, `created_at`, `log_type_id`, `name`, `station_id`, `updated_at`) VALUES (3, 'xx@bb.com', 'xx@bbb.com', '13-10-16', 10, '+ abcdefghij...', 9096, '13-10-16')

what can be the reason that the insert command not included the time
thanks


text:
Q: Remove a word and an associated comma and/or spaces from a string I am given two strings:
s1 = "abc, bcd, abc xyz, abc pq"
s2 = "abc"

I wish to construct a third string that equals s1 with the first occurrence of s2 removed. In addition, if that occurence in s1 is followed by spaces or by a comma and then spaces, those characters are to be removed as well. Lastly, if that occurrence is at the end of s1, the spaces preceding that occurrence are to be removed.
In the example above I wish to produce the string
"bcd, abc xyz, abc pq"

Two more examples:
s2 = "xyz" should produce "abc, bcd, abc abc pq"
s2 = "pq"  should produce "bcd, abc xyz, abc"

You may assume that if s1 contains s2, that part of the string will not be immediately preceded or followed by characters other than a comma or space. For example, you don't have to worry about cases such as
s1 = "abc, bedbug, bed"
s2 = "bed"

A: Comma separated lists can be deconstructed and reconstructed easily:
list = "abc, bcd, abc xyz, abc pq"
list.split(/,\s+/).join(', ')

This means you can delete unwanted elements in the middle:
parts = list.split(/,\s+/)
parts.delete('abc')
parts.join(', ')
# => "bcd, abc xyz, abc pq"

A regular expression to do the substitution makes for a lot more work here, but you'll notice I used one to do the separation.


text:
Q: mysql SUM Group after max of Date I have 2 tables,
Servis table with
Client_ID
date and
type (0 or 1)
Sales tables with
Client_ID
date and
product
I need to crate I table that groups Client ID,  calculates sum of product, but only data after last date on Servis table, with type 1
Client | Sum
-------+------
1      | 32
4      | 2