text:
Q: I'm trying to code a number guessing game I got up to here, but I still need to use while loop somehow. "want to play again(y/n)" and "Illegal guess. Your guess must be between 1 and 200.Try again. Your guess?" don't seem to work. Please help me with the while/do-while loop and fix my two problems above. Thank you.
#include <stdio.h>

int main()
{
    int i,number,guess,tries=5,answer;

    printf("Welcome to the game of Guess It!\nI will choose a number between 1 and 200.");
    printf("\nYou will try to guess that number.If you guess wrong, I will tell you if you guessed too high or too low.");
    printf("\nYou have 5 tries to get the number.\n\nOK, I am thinking of a number. Try to guess it.");

    srand(time(NULL));
    number = rand() % 200 + 1;

    for (i=0;i<tries;i++) {
        printf("\n\nYour guess? ");
        scanf("%i",&guess);

        if (guess==number) {
            printf("**** CORRECT  ****\n\nWant to play again(y/n) ");
            scanf("%i",&answer);

            if (answer=='y') {
                return (i=0);
            }
            else (answer=='n'); {
                printf("Goodbye, It was fun. Play again soon.");
            }

        }
        else if (guess>number) {
            printf("Too high!");
        }
        else if (guess<number) {
            printf("Too low!");
        }
        else (guess>200); {
            printf("Illegal guess. Your guess must be between 1 and 200.\nTry again. Your guess?");
        }
    }

    printf("\n\nSorry, you ran out of tries.\n\nWant to play again?(y/n) ");
    scanf("%i",&answer);

    if (answer=='y') {
        return (i=0);
    }
    else if (answer=='n'); {
        printf("Goodbye, It was fun. Play again soon.");
    }

    return 0;
}

A: First, and most important, turn on warnings. You have several elementary mistakes in your code that would be caught with compiler warnings. They're unfortunately off by default. -Wall turns on the basic warnings. It's not "all" warnings, because this is C! -fsanitize=address -Wall -Wshadow -Wwrite-strings -Wextra -Wconversion -std=c99 -pedantic is a good set of warnings to work with.

You could put a loop around the loop, but that rapidly gets hard to maintain. Instead, put the game into a function and loop around that.
void do_game(int tries) {
    int number = rand() % 200 + 1;

    for (int i=0; i < tries; i++) {
        int guess;
        printf("\n\nYour guess? ");
        scanf("%i",&guess);

        if (guess == number) {
            printf("**** CORRECT  ****\n\n");
            return;
        }
        else if (guess > number) {
            printf("Too high!");
        }
        else if (guess < number) {
            printf("Too low!");
        }
        else if (guess > 200) {
            printf("Illegal guess. Your guess must be between 1 and 200.\nTry again. Your guess?");
        }
    }

    puts("\n\nSorry, you ran out of tries.\n\n");
    return;
}

Note how the game only has to concern itself with the game. No other logic or questions about playing another game. And it can immediately return when the game is over.
Then the rest of the program is pretty simple. Run the game in an infinite loop, break out of it when you're done.
int main() {
    printf("Welcome to the game of Guess It!\nI will choose a number between 1 and 200.");
    printf("\nYou will try to guess that number.If you guess wrong, I will tell you if you guessed too high or too low.");
    printf("\nYou have 5 tries to get the number.\n\nOK, I am thinking of a number. Try to guess it.");

    srand(time(NULL));

    while(1) {
        do_game(5);

        char answer;
        printf("Want to play again?(y/n) ");
        scanf("%c",&answer);

        if (answer == 'n') {
            printf("Goodbye, It was fun. Play again soon.");
            break;
        }
    }

    return 0;
}

There's a problem, and it's scanf. It's always scanf. scanf is such a problem, there's a whole FAQ for it.
scanf("%i") reads a single integer but not the following newline. That newline, and any other extra input, hangs around on stdin. A later scanf("%c", &answer); might then read that newline instead of their answer.
scanf("%i\n") does not solve the problem. That tells scanf to read an integer, then a newline, then look for another non-whitespace character. scanf is weird.
You're much better off reading the whole line with fgets and parsing it with sscanf. You can write a little utility function for that which gets into variadic arguments.
void line_scanf( const char *fmt, ... ) {
    // Get the list of arguments.
    va_list args;
    va_start(args, fmt);

    // Read a line.
    char line[256];
    fgets(line, sizeof(line), stdin);

    // Scan the line like sscanf() but with a va_list.
    vsscanf( line, fmt, args );

    // Close the list of arguments.
    va_end(args);
}

Then use it just like scanf. It guarantees to read the whole line and not leave newlines or partial input on the buffer.
    int guess;
    printf("\n\nYour guess? ");
    line_scanf("%i",&guess);

A: This is only a partial answer, but it can be a starting point. You really should have a reliable input function. Your scanf() won't do, even if you fix the obvious errors trying to get a character using %i, which is for integers. I won't go into details here, I wrote a document on this. (Basically, you will at least run into problems with unparsable input that scanf() will just leave unread.)
Here's an example how you could do reliable input for your usecase with comments along the way:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define INVALIDNUMBER -1
#define READERROR -2

int readPositiveNumber(void)
{
    char buf[64];

    // read a line:
    if (!fgets(buf, 64, stdin)) return READERROR;
    size_t len = strlen(buf);

    // line was empty -> invalid:
    if (!len) return INVALIDNUMBER;

    // line was not complete (last character isn't newline):
    if (buf[len-1] != '\n')
    {
        // read the rest of the line
        do
        {
            if (!fgets(buf, 64, stdin)) return READERROR;
        } while (!buf[strcspn(buf, "\n")]);

        // input was invalid
        return INVALIDNUMBER;
    }

    // convert to number:
    char *endptr;
    long num = strtol(buf, &endptr, 10);

    // endptr == buf means no characters could be parsed as a number,
    // endptr doesn't point to newline means there were non-numeric characters later:
    if (endptr == buf || *endptr != '\n') return INVALIDNUMBER;

    // if result is out of range of int or is negative -> invalid:
    if (num > INT_MAX || num < 0) return INVALIDNUMBER;

    return (int)num;
}

int main(void)
{
    fputs("Enter a number between 1 and 200: ", stdout);
    int number = readPositiveNumber();
    if (number == READERROR) return EXIT_FAILURE;

    while (number < 1 || number > 200)
    {
        fputs("Enter a valid number between 1 and 200: ", stdout);
        number = readPositiveNumber();
        if (number == READERROR) return EXIT_FAILURE;
    }

    printf("You entered %d.\n", number);
    return EXIT_SUCCESS;
}

Try to understand this function, read the manuals for functions you don't know or understand (google "man strtol" for example will find you a manual page for strtol()).
For reading your yes/no response, use fgets() as well, but of course this function will look different, like check if the input is only 1 character (the second one has to be '\n') and return this one character.

just because it's a bit of fun, here's a possible whole game working robustly:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define INVALIDINPUT -1
#define READERROR -2

static int readLine(char *buf, size_t bufsize)
{
    if (!fgets(buf, bufsize, stdin)) return READERROR;
    size_t len = strlen(buf);
    if (!len) return INVALIDINPUT;
    if (buf[len-1] != '\n')
    {
        do
        {
            if (!fgets(buf, bufsize, stdin)) return READERROR;
        } while (!buf[strcspn(buf, "\n")]);
        return INVALIDINPUT;
    }
    return 0;
}

static int readPositiveNumber(void)
{
    char buf[64];
    int rc = readLine(buf, 64);
    if (rc < 0) return rc;
    char *endptr;
    long num = strtol(buf, &endptr, 10);
    if (endptr == buf || *endptr != '\n') return INVALIDINPUT;
    if (num > INT_MAX || num < 0) return INVALIDINPUT;
    return (int)num;
}

static int readYesNo(void)
{
    char buf[64];
    int rc = readLine(buf, 64);
    if (rc < 0) return rc;
    if (buf[0] == 'y' || buf[0] == 'Y')
    {
        if (buf[1] == '\n') return 1;
        if ((buf[1] == 'e' || buf[1] == 'E')
                && (buf[2] == 's' || buf[2] == 'S')
                && buf[3] == '\n') return 1;
        return INVALIDINPUT;
    }
    if (buf[0] == 'n' || buf[0] == 'N')
    {
        if (buf[1] == '\n') return 0;
        if ((buf[1] == 'o' || buf[1] == 'O')
                && buf[2] == '\n') return 0;
        return INVALIDINPUT;
    }
    return INVALIDINPUT;
}

int main(void)
{
    srand(time(0));

    for (;;)
    {
        int number = rand() % 200 + 1;
        int tries = 5;
        int found = 0;
        while (tries--)
        {
            int guess = INVALIDINPUT;
            while (guess < 1 || guess > 200)
            {
                fputs("guess [1..200]: ", stdout);
                guess = readPositiveNumber();
                if (guess == READERROR) return EXIT_FAILURE;
            }
            if (guess == number)
            {
                puts("Correct!");
                found = 1;
                break;
            }
            else if (guess < number) puts ("Too low!");
            else puts("Too high!");
        }
        if (!found)
        {
            puts("No luck!");
        }
        int yn = INVALIDINPUT;
        while (yn < 0)
        {
            fputs("play again (y/n)? ", stdout);
            yn = readYesNo();
            if (yn == READERROR) return EXIT_FAILURE;
        }
        if (!yn)
        {
            puts("Bye!");
            return EXIT_SUCCESS;
        }
    }
}

A: This exercise is an exercise to ingrain in your mind why scanf is generally a bad choice for taking mixed user input! You can do it, but you must be very careful to account for any characters that remain in the input buffer (i.e. stdin) -- especially when taking character input... Why?
When you enter a value that is read by scanf, the '\n' will always remain in the input buffer (unless accounted for in your format string). Further, on a failed conversion -- all characters will remain in the input buffer. Further, the user can do something stupid like entering "4 is my guess" when prompted leaving is my guess\n for you to deal with.
Further, what if the user cancels input by pressing ctrl + d (or ctrl + z on windoze) generating a manual EOF? You must account for all possibilities for each and every input.
You must also use the correct format specifier to read input. You are not going to read 'y' or 'n' with %d or %i. When you want to read an int use %d when you want to read a char, use %c. You must also take into account that %c never skips leading whitespace.
(you beginning to understand why it's better to use fgets and then call sscanf for user input??)
How do you handle the characters that remain in the input buffer? Well generally you will use getchar() to read until you have read '\n' (generated by pressing Enter) or until EOF is encountered. You can make it easy on yourself by writing a short function like the following:
/* empty characters that remain in stdin */
void fflushstdin ()
{
    for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
}

If you call fflushstdin after each input, you will always take care of any characters that remain. If you know chars remain from a prior input that have not been removed, then call it before taking input.
Don't use magic numbers in your code (e.g. 1, 5, 200), instead define any needed constants at the beginning of your code and use the constants in your code. Why? If they change, then you have a single readily accessible place to change them and you don't have to go picking though your code to find them. You can use a #define or an enum like the following:
enum {LOW = 1, TRIES = 5, HIGH = 200 };

The remainder of your problems are simply logic problems that you can work out. Incorporating the above, you can handle (what I think you are attempting to do) as follows:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum {LOW = 1, TRIES = 5, HIGH = 200 };

/* empty characters that remain in stdin */
void fflushstdin ()
{
    for (int c = getchar(); c != '\n' && c != EOF; c = getchar()) {}
}

int main (void) {

    int i, number, guess, ret;
    char answer;

    printf ("Welcome to the game of Guess It!\n"
            "I will choose a number between %d and %d.\n"
            "You will try to guess that number.\n"
            "I will tell you if you guessed too high or too low.\n"
            "You have %d tries to get the number.\n\n"
            "OK, I am thinking of a number. Try to guess it.\n\n",
            LOW, HIGH, TRIES);

    srand(time(NULL));

    while (1) {                         /* outer loop until user quits  */
        number = rand() % HIGH + 1;     /* set number INSIDE loop       */
        for (i = 0; i< TRIES; i++) {    /* loop for set number of TRIES */

            while (1) {      /* validate user guess, handle cancelation */
                printf ("Your guess no. %d? ", i + 1);      /* prompt   */
                if ((ret = scanf (" %d", &guess)) != 1) { /* chk return */
                    if (ret == EOF) {          /* check for cancelation */
                        printf ("input canceled, exiting.\n");
                        return 0;
                    }
                    fprintf (stderr, "  error: invalid input.\n");
                    fflushstdin();    /* empty chars remaining in stdin */
                    continue;
                }
                if (guess < LOW || guess > HIGH)        /* check limits */
                    printf("Illegal guess. Your guess must be between "
                           "%d and %d.\nTry again. Your guess?", LOW, HIGH);
                break;
            }

            if (guess == number) {  /* correct answer */
                printf ("\n**** CORRECT  ****\n\nWant to play again(y/n) ");
                fflushstdin();
                /* validate answer, you are reading a `char` NOT `int` */
                while ((ret = scanf (" %c", &answer)) != 1 ||
                        (answer != 'y' && answer != 'n')) {
                    fprintf (stderr, "error: invalid answer, play again (y/n) ");
                    if (ret == EOF) {          /* check for cancelation */
                        printf ("input canceled, exiting.\n");
                        return 0;
                    }
                    fflushstdin();    /* empty chars remaining in stdin */
                }
                if (answer == 'y')  /* use goto for breaking nested loops */
                    goto done;

                printf ("Goodbye, It was fun. Play again soon.\n"); /* no */
                return 0;
            }

            if (guess > number)         /* provide > and < feedback */
                printf ("Too high!\n");

            if (guess < number)
                printf("Too low!\n");
        }
        printf ("Sorry, you exhausted all your tries, number was: %d\n"
                "play again (y/n) ", number);

        fflushstdin();
        /* validate answer, you are reading a `char` NOT `int` */
        while ((ret = scanf (" %c", &answer)) != 1 ||
                (answer != 'y' && answer != 'n')) {
            fprintf (stderr, "error: invalid answer, play again (y/n) ");
            if (ret == EOF) {
                printf ("input canceled, exiting.\n");
                return 0;
            }
            fflushstdin();
        }
        if (answer != 'y')
            break;

        done:;  /* goto lable to play again after correct asnwer */
    }

    return 0;
}

Example Use/Output
$ ./bin/guess
Welcome to the game of Guess It!
I will choose a number between 1 and 200.
You will try to guess that number.
I will tell you if you guessed too high or too low.
You have 5 tries to get the number.

OK, I am thinking of a number. Try to guess it.

Your guess no. 1? onehundred
error: invalid input.
Your guess no. 1? 100
Too low!
Your guess no. 2? 150
Too high!
Your guess no. 3? 125
Too low!
Your guess no. 4? 137
Too high!
Your guess no. 5? 131
Too low!
Sorry, you exhausted all your tries, number was: 132
play again (y/n) y
Your guess no. 1? 100
Too low!
Your guess no. 2? 150
Too low!
Your guess no. 3? 175
Too low!
Your guess no. 4? 187
Too high!
Your guess no. 5? 181

**** CORRECT  ****

Want to play again(y/n) y
Your guess no. 1? 100
Too low!
Your guess no. 2? 150
Too high!
Your guess no. 3? 125
Too high!
Your guess no. 4? 112
Too high!
Your guess no. 5? 106
Too low!
Sorry, you exhausted all your tries, number was: 110
play again (y/n) n

Note, the above handles stupid user input (like onehundred) and adds number to the failure output to let the user know what he missed.
Look things over and let me know if you have further questions.

A: scanf("%i", ...) reads integers in base 10, not characters or strings.
You need to organize your loops.  You have 2 main loops, one that runs while the user wants to keep playing, and another that runs while the a game is on.
You program in a nutshell:
int main()
{
  // loop until player has had enough
    // pick a number
    // game loop :
      // get a number from user:
        // user entry loop:
          // print prompt
          // get user entry
          // validate
       // loop number from user: until 0 <= entry <= 200

     // if number is ok
       // user has won, exit game loop
     // if too low
       // say 'low'
     // if too high
       // say high
     // if # of attempts > MAX
       // say 'lost' exit game loop
   // end game loop

   // want to contine?
     // user entry loop:
       // print prompt
       // get user entry
       // validate
     // loop user entry loop until 0 <= entry <= 200
  // end loop
}

You could start your loops within main a bit like this:
int attempts;
char yesno = 0;
int guess;

do                    // loop until player has had enough
{
   // generate a number here

   attempts = 0;
   while(1)           // loop while game is on
   {
     while (1)        // loop until user entered a valid entry
     {
        // prompt
        // get user guess
        if (0 <= guess && guess <= 200)
          break;
     }

    if (guessed right)
     {
        // game over!
        break;
     }

     // tell if high or low.

     if (++attempts <= MAX)
     {
        // game over!
        break;
     }
   }

   do                  // loop until user entered a valid entry.
   {
     printf("Another game (y/n)?");
     yesno = fgetc();
   } while(yesno != 'y' && yesno != 'n');  // could make case-insensitive ?

} while (yesno != 'n');

There are probably as many ways to do this as there are numbers between 0 and 200.  A good strategy is to start by writing comments in your C file that describe step by step what the program needs to do.  Going through them one by one is much easier than having the program only in your head, especially when you are starting to code.  It will get easier with time as you get used to juggle the concepts and basic blocks your mind.


text:
Q: how to perform operation after successfully starting elastic search I have to create a shell script to start elastic search from shell command and after successful start of elastic search I have to perform certain operation.
In my case elastic search is starts but after that nothing happens not even echo command works.
Here is the code sample :
elasticsearch-1.7.2/bin/elasticsearch

res=$( curl -w %{http_code} -s --output /dev/null http://localhost:9200)
if [ $res -eq 200 ]
then
        echo "Elastic search running successfully"
        Perform operation
fi

Thanks,

A: A shell script executes 1 line at time and doesn't move onto the next line (command) until the current one has completed.
You can use the & char to run a command in the background, then the remaining commands can be executed in sequence.
Something like
#!/bin/bash
elasticsearch-1.7.2/bin/elasticsearch &

/bin/sleep 30 # change to num secs needed for ES to start correctly

res=$( curl -w %{http_code} -s --output /dev/null http://localhost:9200)
if [ $res -eq 200 ]
then
        echo "Elastic search running successfully"
        Perform operation
fi

might help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does the Run dialog know where applications are? As a power user, I frequently use the Run dialog.
I can understand why the following commands work, as they are in the PATH environment variable.
mspaint
diskmgmt.msc
explorer

These commands also work in CMD.
The commands below work in run, but they are not in the PATH, and they don't work in CMD.
firefox
winword
iexplore

How does Run know where these files are?

A: When you execute a command from Run dialog, the system looks at the App Paths registry key here:
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths

and
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths

EXAMPLE
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\filezilla.exe

(default) value data has the full path to the executable.
If it's not found, it looks at each folder included in the PATH.
Whereas the Command Prompt doesn't reference these registry keys. It only searches the PATH.

A: w32sh's answer correctly points out that the extra keys searched by the Run dialog are here:

*

*HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\

*HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\

There is official documentation for these paths.
An important fact about these keys is that the name of the key (e.g. "filezilla.exe") doesn't have to match the full path in any way. Under Windows 7, the value can even be a simple command-line, similar to what can be used as the "target" of a shortcut.
For instance, I used to have this in my registry:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\jedit.exe]
@="\"C:\\WINDOWS\\system32\\javaw.exe\" -Xms24M -Xmx512M -jar \"C:\\Program Files\\jEdit\\jedit.jar\" -reuseview"

I can't seem to make this work in Windows 10, but you can still point at any file, including a batch file, e.g.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\jedit.exe]
@="C:\\Program Files\\jEdit\\run-jedit.bat"

That allows you to type "jedit" or "jedit C:\foo\bar\something.txt" to run the JVM with appropriate options and launch/reuse jEdit.
As far as I can see, the key name must end in ".exe", so to create an alias of "abc", you create a key "abc.exe", even if it's not pointing to a ".exe" file.

A: There's an environment variable called PATH, or %PATH% in the command line. It contains a series of locations to search through.


text:
Q: "multiplication table" with custom function using python I'm running a one-way ANOVA within 7 groups and would like to create a matrix containing Cohen's d for each couple of groups. To generalize the problem, it's creating a matrix based on one vector and using a custom function for the values. A similar example is a multiplication table, where the vector is range(1,11) and the function is multiplication. This is how it suppose to look:

A: you mean something like this:
f = lambda x,y: x*y
a = [1,2,3,4]
print([[f(x,y) for x in a] for y in a])

output:
[[1, 2, 3, 4],
 [2, 4, 6, 8],
 [3, 6, 9, 12],
 [4, 8, 12, 16]]


text:
Q: Inverse a coefficient of a table I have a file with 256 coefficient and I want to inverse each 64 coefficient of this file and keep the result in another file. I try to program my idea but the result is wrong.
int main()
{
    /***********************************inversion coefficients*****************/
    FILE* org = NULL; // original file
    FILE* inv = NULL; // file content inverse coefficient
    float det; // readed coefficient
    float tabinv[256]; // intermediate table witch will content iverse coefficient
    org = fopen("det.txt", "r");
    inv = fopen("inverse.txt", "w");
    int j = 64;
    int p = j;
    int copt = 0;
    while (copt < 256)
    {
        for (int i = j - 64; i < j; i++)
        {

            fscanf(org, "%f", &det);

            tabinv[p - 1 - i] = det;

            copt++;

        }

        p = p + 64;

        j = p;
    }
    for (int k = 0; k < 256; k++){
        fprintf(inv, "%f\n", tabinv[k]);

    }
    fclose(org);
    fclose(inv);
    return 0;
}

A: You have Fix in this line-
 tabinv[p - 1 - i] = det; // Don't use same variable i.

Normally From the expression int i = j - 64,when p=j=64, i=0, that time it stores the value from tabinv[63] to tabinv[0]. But when p=j=128, i=64, that time also it start stores the value from tabinv[63] to tabinv[0]. You need to fix this to avoid the error.
Try the following change-
for (int i = j - 64,int k = 0; i < j; i++,k++) // Fix 1
{

    fscanf(org, "%f", &det);

    tabinv[p - 1 - k] = det; // Fix 2

    copt++;

}


text:
Q: Does there exist $\lambda_{\sigma(1)}$ such that $\mu(A\cap\{\lambda_{\sigma(1)}\neq0\})>0$? Let $(\mathcal F,\Omega,\mu)$ be a measure space and $A\subseteq\Omega$ such that $\mu(A)>0$. Let $L^0$ be the space of all measurable functions.
We say $X_1,\ldots,X_k\in(L^0)^d=\prod_{k=1}^dL^0$ are linearly independent on $A$ if $(0,\ldots,0)$ is the only vector $(\lambda_1,\ldots,\lambda_k)\in1_A(L^0)^d$ satisfying
$$\lambda_1X_1+\ldots+\lambda_kX_k=0$$
Suppose $X_1,\ldots,X_k\in(L^0)^d$ are linearly independent on $A$ and
$$\text{span}_A\{X_1,\ldots,X_k\}\subseteq\text{span}_A\{Y_1,\ldots,Y_l\}$$
for some $Y_1,\ldots,Y_l\in(L^0)^d$.
Does there exist a $\sigma(1)\in\{1,\ldots,l\}$ such that
$$\mu(A\cap\{\lambda_{\sigma(1)}\neq0\})>0?$$


text:
Q: Does Apache basic authentication defend brute force attacks? Will it shut down & lock up after repeated false password tries, and/or will it add lags in-between retries? Or does this depend on which modules you or your provider install? Thanks!

A: default Apache installation does not do that.
usually this is better done by your web application (eg, PHP/JSP) for account attack.
for network attack, better not for web servers because it's hard to identify the source due to so many anonymous / transparent proxy / VPN / NAT stuff. once you've implement that, you'd usually get lots of "why I can't connect" complains...


text:
Q: Crossings in knots are counted more than once I'm new to the knots library for TikZ and I have problems drawing some simple knots.  With the MWE below, the library claims there are 12 crossings although in reality there are only four.  Furthermore, some of the crossings receive more than one number and I can't figure out how to reliably control the flipping.  \flipcrossings{2} doesn't seem to have any effect on the crossing numbered 2 while \flipcrossings{9} does.  I guess this is because 9 is the highest number this particular crossing got, but that's not easy to see as there are several numbers atop each other.
I tried other options for the knot environment and I also tried other ways to draw the strand (for example with to or with Bézier curves instead of Hobby curves) but that doesn't seem to solve the problem.
What am I doing wrong?
\documentclass[tikz, border=5mm]{standalone}
\usetikzlibrary{knots,hobby}
\begin{document}
\begin{tikzpicture}
  \begin{knot}[draft mode=crossings,consider self intersections=no splits,ignore endpoint intersections=false]
    \strand[closed hobby] plot coordinates {(2.5,5) (2.5,2) (2.5,0.5) (0.5,2.5) (2.5,4) (4.5,2.5) (2.5,0.5) (2.5,2)};
  \end{knot}
\end{tikzpicture}
\end{document}

FWIW, this is what I see (MiKTeX on Windows, updated today):

A: I rummaged around a bit more and found a comment from Andrew Stacey (the package author) here where he says:

The algorithm behind the knots package works best when the crossing is not at the endpoint of a section of the path.

So, I modified my curve a bit and now it works (except for the pseudo-crossing at the start which doesn't hurt):
\documentclass[tikz, border=5mm]{standalone}
\usetikzlibrary{knots,hobby}
\begin{document}
\begin{tikzpicture}
  \begin{knot}[draft mode=crossings,consider self intersections=no splits,ignore endpoint intersections=false]
    \strand[closed hobby] plot coordinates {(2.5,5) (1.6,4) (2.75,1.2) (2,0.2) (0.5,2.5) (2.5,4) (4.5,2.5) (3,0.2) (2.25,1.2) (3.4,4)};
  \end{knot}
\end{tikzpicture}
\end{document}


text:
Q: How to access options inside apos.define? apostrophe-workflow has the following:
public/js/user.js
apos.define('apostrophe-workflow', {

  [...]

  construct: function(self, options) {

    self.locales = options.locales;
    self.locale = options.locale;
    [...]

I searched quite a while and did not manage to find the reason why this construct method has access to the options object. I tried browserCall but am not sure how to use this properly.
My assets are pushed using pushAsset, too. But they do not have access to the options after apos.create.
Edit: Example scenario:
A simple module that pushes one script to the browser.
module/index.js
construct: function(self, options) {
  self.pushAsset('script', 'name', {when: 'always'});
}

And takes one option.
app.js
modules: {
  'module': {
    option: 'Option'
  }
}

The script should use this option on construct.
module/public/js/script.js
apos.define('module-script', {
  construct: function(self, options) {
    console.log(options.option); // Print 'Option' to console.
  }
});

Another module will call apos.create('module-script').
I hope it's clear.

A: You can solve (at least) this two ways depending on the structure you want.
1. Explicit browser options
You can explicitly pass options to the browser from your modules configuration by wrapping them in a browser object from the root of the module's config.
in lib/modules/layout-widgets/index.js
module.exports = {
    extend: 'apostrophe-widgets',
    label: 'Layout',
    browser: {
      coolArray: [3, 2, 1]
    }
  }

This will get merged into the options passed to your browser side JS of the module automatically.
then in /lib/modules/layout-widgets/public/js/always.js
apos.define('layout-widgets', {
  extend: 'apostrophe-widgets',
  construct: function (self, options) {
    self.play = function ($widget, data, options) {
      console.log(self.options.coolArray);
    }
  }
});

2. Super'ing getCreateSingletonOptions
If you don't like the syntax of separating your browser options from your main options, you can always override the method responsible for teeing up the browser side module's default options by copying it, invoking it, and adding on to it.
in lib/modules/layout-widgets/index.js
module.exports = {
  extend: 'apostrophe-widgets',
  label: 'Layout',
  coolArray: [3,2,1],
  construct: function(self, options) {

    // copy the method
    var superGetCreateSingletonOptions = self.getCreateSingletonOptions;

    // redefine it
    self.getCreateSingletonOptions = function (req) {

      // invoke the original method and save the result
      var browserOptions = superGetCreateSingletonOptions(req);

      // add on to the default results with whatever you want
      browserOptions.coolArray = self.options.coolArray;
      browserOptions.somethingElse = 'hey this is fun';

      return browserOptions;
    };
  }
};

then, again, in /lib/modules/layout-widgets/public/js/always.js
apos.define('layout-widgets', {
  extend: 'apostrophe-widgets',
  construct: function (self, options) {
    self.play = function ($widget, data, options) {
      console.log(self.options.coolArray);
      console.log(self.options.somethingElse);
    }
  }
});


text:
Q: ActionView::Template::Error (undefined method `remote_image_url Getting this error
in this page

    <%= f.label :remote_image_url, "or image URL" %>
    <%= f.text_field :remote_image_url %>

Model
class Gamepic < ActiveRecord::Base
  belongs_to :gallery
  mount_uploader :gamepic, GamepicUploader

  private
    def Gamepic_params
      params.require(:gamepic).permit(:gameid, :gamename, :gamepic, :remote_image_url)
  end
end


text:
Q: I have written a code for creating a linked list. While printing the list items I am getting SIGSEV error. How do we fix it? I know I have done a silly mistake and to not make it again in the future I want to know why this error is showing up in the following code. I have already read on the internet that it is caused when our program is trying to access memory block which is not yet created but I cannot find where it is occurring in my program.
Thank You, Guys.
struct node
{
  int value;
  struct node *next;
};

typedef struct node Node;

Node *createNewNode(int value)
{
  Node *result = new Node;
  result->value = value;
  result->next = NULL;
  return result;
}

Node *insertHeadNode(Node **head, Node *nodeToInsert)
{
  nodeToInsert->next = *head;
  *head = nodeToInsert;
  return nodeToInsert;
}

void print_list(Node *head)
{
  Node *temp = head;
  while (temp != NULL)
  {
    cout << temp->value << "->";
    temp = temp->next;
  }
  cout << endl;
}

int main()
{
  int value, i;
  Node *head;
  Node *tmp;

  while (i < 5)
  {
    cout << "Enter the value of the linked list: ";
    cin >> value;
    tmp = createNewNode(value);
    insertHeadNode(&head, tmp);
    i++;
  }

  print_list(head);

  return 0;
}

One more thing. I have dynamically created a struct in the createNewNode function. So we do delete it at the end of our program, right?

A: You have multiple parts in your code that result in undefined behavior.
You never initialize i so doing i < 5 isn't valid.
You never initialize Node *head so that one also holds an indeterminate value, that value is assigned to nodeToInsert->next in insertHeadNode.
So also cout << temp->value << "->"; would be invalid, at the point when temp = temp->next has reaced the node for which you assinged that indeterminate to next.


text:
Q: Сначала считать 1.txt потом 2.txt Есть два txt файла:
В 1.txt
1
2
3

Во 2.txt то же самое.
Как мне считать с начало первый потом второй то есть когда считался полностью первый то его считывание через foreach остановилось, и код начал считывать 2.txt.
Написал такой код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;

    namespace foreach_txt
    {
        class Program
        {
            static void Main(string[] args)
            {
                string[] files1 = File.ReadAllLines(@"C:\Users\Wiz\Desktop\1.txt");
        string[] files2 = File.ReadAllLines(@"C:\Users\Wiz\Desktop\2.txt");
        foreach (var lines1 in files1)
        {
            Console.WriteLine(lines1);
        }
        foreach (var lines2 in files2)
        {
            Console.WriteLine(lines2);
        }
        Console.ReadKey();
            }
        }
    }

A: foreach (var lines1 in files1)
{
    Console.Write(lines1);
}
foreach (var lines2 in files2)
{
    Console.Write(lines2);
}

А так не нужно лишний раз переименовывать:
foreach (var lines in files1)
{
    Console.Write(lines);
}
foreach (var lines in files2)
{
    Console.Write(lines);
}


text:
Q: No runnable methods on Android JUnit4 Instrumentation Tests I am new to Instrumentation Testing on Android and was learning from the sample at https://github.com/googlesamples/android-testing/tree/master/runner/AndroidJunitRunnerSample to use AndroidJUnit4.
That code works perfectly.
Trying to implement the same login on my project, however, I get the following exception:
Running tests
Test running started
java.lang.Exception: No runnable methods
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
at android.support.test.internal.runner.junit4.AndroidJUnit4ClassRunner.<init>(AndroidJUnit4ClassRunner.java:38)
at android.support.test.runner.AndroidJUnit4.<init>(AndroidJUnit4.java:36)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.support.test.internal.runner.junit4.AndroidAnnotatedBuilder.buildAndroidRunner(AndroidAnnotatedBuilder.java:57)
at android.support.test.internal.runner.junit4.AndroidAnnotatedBuilder.runnerForClass(AndroidAnnotatedBuilder.java:45)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runner.Computer.getRunner(Computer.java:40)
at org.junit.runner.Computer$1.runnerForClass(Computer.java:31)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:101)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:87)
at org.junit.runners.Suite.<init>(Suite.java:81)
at org.junit.runner.Computer.getSuite(Computer.java:28)
at android.support.test.internal.runner.TestRequestBuilder.classes(TestRequestBuilder.java:791)
at android.support.test.internal.runner.TestRequestBuilder.build(TestRequestBuilder.java:754)
at android.support.test.runner.AndroidJUnitRunner.buildRequest(AndroidJUnitRunner.java:341)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:238)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1853)

My AndroidTestSuite looks like:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({InstrumentationTestSuite.class})
public class AndroidTestSuite {}

And my InstrumentationTestSuite looks like:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({LoginInstrumentationTest.class})
public class InstrumentationTestSuite {}

My LoginInstrumentationTest is
@RunWith(AndroidJUnit4.class)
@LargeTest
public class LoginInstrumentationTest {

    @Rule
    public ActivityTestRule<LoginActivity> mActivityRule = new ActivityTestRule<>(
        LoginActivity.class);

    @Test
    public void attemptToLogin() {
        login("filipebarretto@xxxxxxxxxx.com", "12345678");
    }

    private void login(String email, String password) {

        // Enter user email
        onView(withId(R.id.email)).perform(typeText(email),
            closeSoftKeyboard());

        // Enter user password
        onView(withId(R.id.password)).perform(typeText(password),
            closeSoftKeyboard());

        // Click on the login button
        onView(withId(R.id.email_sign_in_button)).perform(click());

        // Testing
        onView(withId(R.id.email)).check(matches(withText(email)));

    }
}

From what I search, usually the error I'm getting is due to a missing @Test before my method.
The difference I noticed between my code and the one I'm learning from is the gradle version, which I use 1.5.0 and they use 2.0.0-beta2.
I also found that my Instrumentation.java that is called during the test has several "Cannot resolve symbol" error with I can't find the reason, since I use the same dependencies as the sample code.
Any one know what could be the reason of the No runnable methods exception and how to solve it?

A: I finally solved the problem. The problem was that I was planning on running unit tests also, not just instrumentation tests.
I had a class UnitTestSuite like:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({LoginUnitTest.class})
public class UnitTestSuite {}

And LoginUnitTest didn't implement any tests.
For some reason, even though UnitTestSuite wasn't called from AndroidTestSuite, it tried to run and returned No runnable methods, since LoginUnitTest had no tests implemented. I've added unit tests and now the tests work perfectly.


text:
Q: Library function to find difference between two lists - OCaml Is there a library function to find List1 minus elements that appear in List2?  I've been googling around and haven't found much.
It doesn't seem too trivial to write it myself. I've written a function to remove a specific element from a list but that's much more simple:
let rec difference l arg = match l with
| [] -> []
| x :: xs ->
    if (x = arg) then difference xs arg
    else x :: difference xs arg;;

A: Will this do?
let diff l1 l2 = List.filter (fun x -> not (List.mem x l2)) l1

A: What I ended up actually doing was just writing another function which would call the first one I posted
let rec difference l arg = match l with
    | [] -> []
    | x :: xs ->
        if (x = arg) then difference xs arg
        else x :: difference xs arg;;

let rec list_diff l1 l2 = match l2 with
    | [] -> l1
    | x :: xs -> list_diff (difference l1 x) xs;;

Although the solution I accepted is much more elegant


text:
Q: Get max date from collection in mongoDB by Spring Boot repository I need to get the max date and the field "sendingSystemCode" need to be equal to '999' from collection in MongoDB (Compass) by Spring Boot repository.
For now I did it like that:
@Repository
public interface ControlFutureTransactionRepository extends
MongoRepository<ControlFutureTransactionEntity, Integer>
{
    @Query("{'sendingSystemCode': {$eq: 999}}")
    List<ControlFutureTransactionEntity> getControlFutureTransactionBySendingSystemCode();
}

And the max date I get by a simple loop in the code, and I want to make the code faster by one query, to add the max date to the method in the repository.
for some reason this option is hard to find in google.
Thanks a lot !

A: You have two options:
Option 1 (aggregation framework):
db.collection.aggregate([ {$match:{sendingSystemCode:999}} , {$group:{_id:"the_max_date" ,maxDate:{$max:"$createdDate"}}}        ])

Option 2 ( find/sort/limit):
db.collection.find({sendingSystemCode:999}).sort({createdDate:-1}).limit(1)


text:
Q: After checkout to another branch and use git pull,Git merge files from previous branch I have a following code in Jenkins which help me making a patch
git -C $PROJECT fetch
strTmp=$(git -C $PROJECT diff origin/$BRANCH..origin/master --name-only)
echo "strTmp = $strTmp"

if [ -n "$strTmp" ]; then

git -C $PROJECT reset --hard
git -C $PROJECT checkout $BRANCH
git -C $PROJECT pull

But from time to time i see what previous branch was merged in my local branch
HEAD is now at dac33 Merge remote-tracking branch 'origin/master' into release/DEV-11111
branch 'release/DEV-19999' set up to track 'origin/release/DEV-19999'.
Switched to a new branch 'release/DEV-19999'
Merge made by the 'ort' strategy.
 CHK_CL_IP   | 28 ++++++++++++++++
 RED_IP | 29 +++++++++++++++++
 CR_P_IP | 46 +++++++++++++++++++++++++++
 IP | 29 +++++++++++++++++
 4 files changed, 132 insertions(+)
 CHK_CL_IP
 RED_IP
 CR_P_IP
 IP

Above files a merged from release/DEV-11111 and it's merged when git pull command are executed.
But why?
I was switched to another branch, why files from DEV-11111 are merged into my current branch?
I expected to only files from branch which we switched to are updated from remote


text:
Q: Build Server Best Practices I heard google has some automated process like that:

*

*When you check in, your code is checked into a temporary location.

*It is built.

*Style checks run.

*Tests run.

*If there are no problems, code goes to actual repository.

*You receive an e - mail containing test results, performance graphs, style check results and whether your code is checked in.

So if you want to learn if you broke something or the great performance gain you expected occurred, you just check in and receive an e - mail telling you what you need to know.
What are your favorite build server best practices?

A: What you described for google is what every basic build process does. Specific projects may have additional needs, for example - how we deploy web applications from staging to production:

*

*Build start

*Live site is taken offline (Apache redirects to different directory holding an "Under construction" page)

*SVN update is ran for production server

*Database schema deltas are ran

*Tests are ran against updated source and schema

*In case of fail: rollback is ran (SVN revert and database schema UNDO)

*Site gets back online

*Build ends

A: On the java platform I have tried every single major CI system there is. My tip is that paying for a commercially supported solution has been the cheapest build system I've ever seen. These things take time to maintain, support and troubleshoot. Especially with a heavy load of builds running all the time.

A: The example workflow you give is similar to the one proposed by TeamCity. The idea being:

*

*Code

*Check in to "pre-test"

*CI server tests the "pre-commit"

*If (and only if) tests pass, the CI server commits the code change to the main repo

It's a religious war but I prefer:

*

*Code - Test - Refactor (loop)

*Commit

*CI server also validates your commit

Every responsible programmer should run all the tests before committing.
The main argument for the first way is that it gurantees that there is no broken code in SCM. However, I would argue that:

*

*You should trust your developers to test before committing

*If tests take to long, the problem is your slow tests, not the workflow

*Developers are keen to keep tests fast

*Relying on CI server to run tests give you false sense of security


text:
Q: Can't get AVFoundation Pause () working in CollectionView In my app I have a collectionViewCell that plays music, In the collectionViewCell class I made the player variable
 var player: AVAudioPlayer?

I also tried:
var player = AVAudioplayer()

I made a method pauseMusic ()
func pauseMusic (){

    if player != nil {
    if player!.playing == true{

    player!.pause()
       }
    }
}

When I call this pauseMusic() method from my FirstViewController in the UIBarButtonItem action, my app crashes
 @IBAction func pauseButton(sender: UIBarButtonItem) {

    var colVW = CollectionViewCell()
    colVW.pauseMusic()
}

I also uploaded this screenshot that shows the error when it crashes
http://nl.tinypic.com/r/t66zir/8
Is anybody familiar with this crash?
I would really appreciate if you could give me some advice!
Additional code:
This func checks which song has to be played, this func lives in the CollectionView. Because of the link between this func and the CollectionViewCell class, I can't move the AVPlayer somewhere else..
func prepareAudios() {

   var songIndexString = (imageOutlet.titleLabel?.text)!
    //println(songIndexString)

    var songIndex = (songIndexString.toInt())!

    println("songIndex: \(songIndex)")

    if musicStopped == true {

        rateButton()
        println("empty")

    } else if var filePath = NSBundle.mainBundle().pathForResource(audioArray[songIndex], ofType: "mp3"){

        var filePathUrl = NSURL.fileURLWithPath(filePath)
        player = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)
        player!.play()

    } else {
        println("Path for audio file not found")
    }
}


text:
Q: Deleting duplicate rows, keeping most recent row by max(datetime) The MySQL statement below selects all rows that have duplicates based on ADDRESS1 and POSTCODE of which the most recent row, INSPECTION_DATE. Essentially it selects all the ones I want to keep.
SELECT COUNT(*), MAX(INSPECTION_DATE), ADDRESS1, POSTCODE, id
FROM epc
GROUP BY ADDRESS1, POSTCODE
HAVING COUNT(*) > 1;

My question is, how do I delete all of the older duplicates, keeping the ones that the above statement returns.

A: http://sqlfiddle.com/#!9/8de866/1
DELETE  e
FROM epc e
INNER JOIN epc max_
ON e.address1 = max_.address1
   AND e.postcode = max_.postcode
   AND e.inspection_date < max_.inspection_date;

UPDATE
http://sqlfiddle.com/#!9/5bd5981/1
DELETE  e
FROM epc e
INNER JOIN epc max_
ON e.address1 = max_.address1
   AND e.postcode = max_.postcode
   AND (e.inspection_date < max_.inspection_date
        OR (e.inspection_date = max_.inspection_date
           AND e.id < max_.id));


text:
Q: MongoDB conditional aggregate query on a HABTM relationship (Mongoid, RoR)? Rails 4.2.5, Mongoid 5.1.0
I have three models - Mailbox, Communication, and Message.
mailbox.rb
class Mailbox
    include Mongoid::Document
    belongs_to :user
    has_many :communications
end

communication.rb
class Communication
    include Mongoid::Document
    include Mongoid::Timestamps
    include AASM

    belongs_to :mailbox
    has_and_belongs_to_many :messages, autosave: true

    field :read_at,     type: DateTime
    field :box,         type: String
    field :touched_at,  type: DateTime
    field :import_thread_id, type: Integer
    scope :inbox, -> { where(:box => 'inbox') }
end

message.rb
class Message
    include Mongoid::Document
    include Mongoid::Timestamps

    attr_accessor :communication_id

    has_and_belongs_to_many :communications, autosave: true
    belongs_to :from_user, class_name: 'User'
    belongs_to :to_user, class_name: 'User'

    field :subject, type: String
    field :body,    type: String
    field :sent_at, type: DateTime
end

I'm using the authentication gem devise, which gives access to the current_user helper, which points at the current user logged in.
I have built a query for a controller that satisfied the following conditions:
Get the current_user's mailbox, whose communication's are filtered by the box field, where box == 'inbox'.
It was constructed like this (and is working):
current_user.mailbox.communications.where(:box => 'inbox')
My issue arrises when I try to build upon this query.  I wish to chain queries so that I only obtain messages whose last message is not from the current_user.  I am aware of the .last method, which returns the most recent record.  I have come up with the following query but cannot understand what would need to be adjusted in order to make it work:
current_user.mailbox.communications.where(:box => 'inbox').where(:messages.last.from_user => {'$ne' => current_user})
This query produces the following result:
undefined method 'from_user' for #<Origin::Key:0x007fd2295ff6d8>
I am currently able to accomplish this by doing the following, which I know is very inefficient and want to change immediately:
mb = current_user.mailbox.communications.inbox
comms = mb.reject {|c| c.messages.last.from_user == current_user}
I wish to move this logic from ruby to the actual database query. Thank you in advance to anyone who assists me with this, and please let me know if anymore information is helpful here.

A: Ok, so what's happening here is kind of messy, and has to do with how smart Mongoid is actually able to be when doing associations.
Specifically how queries are constructed when 'crossing' between two associations.
In the case of your first query:
current_user.mailbox.communications.where(:box => 'inbox')

That's cool with mongoid, because that actually just desugars into really 2 db calls:

*

*Get the current mailbox for the user

*Mongoid builds a criteria directly against the communication collection, with a where statement saying: use the mailbox id from item 1, and filter to box = inbox.

Now when we get to your next query,
current_user.mailbox.communications.where(:box => 'inbox').where(:messages.last.from_user => {'$ne' => current_user})

Is when Mongoid starts to be confused.
Here's the main issue: When you use 'where' you are querying the collection you are on.  You won't cross associations.
What the where(:messages.last.from_user => {'$ne' => current_user}) is actually doing is not checking the messages association.  What Mongoid is actually doing is searching the communication document for a property that would have a JSON path similar to: communication['messages']['last']['from_user'].
Now that you know why, you can get at what you want, but it's going to require a little more sweat than the equivalent ActiveRecord work.
Here's more of the way you can get at what you want:
user_id = current_user.id
communication_ids = current_user.mailbox.communications.where(:box => 'inbox').pluck(:_id)
# We're going to need to work around the fact there is no 'group by' in
# Mongoid, so there's really no way to get the 'last' entry in a set
messages_for_communications = Messages.where(:communications_ids => {"$in" => communications_ids}).pluck(
  [:_id, :communications_ids, :from_user_id, :sent_at]
)
# Now that we've got a hash, we need to expand it per-communication,
# And we will throw out communications that don't involve the user
messages_with_communication_ids = messages_for_communications.flat_map do |mesg|
  message_set = []
  mesg["communications_ids"].each do |c_id|
    if communication_ids.include?(c_id)
      message_set << ({:id => mesg["_id"],
       :communication_id => c_id,
       :from_user => mesg["from_user_id"],
       :sent_at => mesg["sent_at"]})
    end
  message_set
end
# Group by communication_id
grouped_messages = messages_with_communication_ids.group_by { |msg| mesg[:communication_id] }
communications_and_message_ids = {}
grouped_messages.each_pair do |k,v|
  sorted_messages = v.sort_by { |msg| msg[:sent_at] }
  if sorted_messages.last[:from_user] != user_id
    communications_and_message_ids[k] = sorted_messages.last[:id]
  end
end
# This is now a hash of {:communication_id => :last_message_id}
communications_and_message_ids

I'm not sure my code is 100% (you probably need to check the field names in the documents to make sure I'm searching through the right ones), but I think you get the general pattern.


text:
Q: How to remove java.util.concurrent.RejectedExecutionException while using Future Interface I have a controller in which I am using future interface and creating 5 threads in threadpool. This controller is called by an ajax call. When I call this controller the first time it runs fine but if I make the request again it shows the exception below.
  java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@1cbbac9 rejected from java.util.concurrent.ThreadPoolExecutor@53ee53[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 5]

I am posting code how I am calling the tasks.
  private static final ExecutorService threadpool = Executors.newFixedThreadPool(20);
    FactorialCalculator task1 = new FactorialCalculator("A");
    FactorialCalculator task2 = new FactorialCalculator("B");
    FactorialCalculator task3= new FactorialCalculator("C");
    FactorialCalculator task4 = new FactorialCalculator("D");
    FactorialCalculator task5= new FactorialCalculator("E");
    System.out.println("Submitting Task ...");
    Future future1 = threadpool.submit(task1);
    Future future2 = threadpool.submit(task2);
    Future future3 = threadpool.submit(task3);
    Future future4 = threadpool.submit(task4);
    Future future5 = threadpool.submit(task5);
    System.out.println("Task is submitted");

In first request it is running all tasks- A,B,C,D and E but when I make request again it prints submitting tasks but doesn't print Task is submitted. Can someone help out what am I doing wrong.

A: You haven't mentioned specifically which version of Java you're using, but I suspect the relevant classes haven't changed much.  The ThreadPoolExecutor will throw that exception from it's execute method in two cases, both of which rely on the executor's state being SHUTDOWN.
So I am fairly confident that the executor is rejecting your task submissions because it is being shut down at some point.  I notice your code is not telling the whole story, as it looks like the executor is a class field that might be referenced by other methods.  Check whether you're calling shutdown anywhere else.  (Note that the executor will be shut down by its finalizer; though in the block of code you've posted there's no way it will be eligible for garbage collection as it's a final field.)

As a footnote, whenever you're having trouble with code it's useful to provide a SSCCE.  The code you've posted doesn't compile, but after fixing this, it runs successfully.  Are you able to fork my Ideone script and reproduce your problem?


text:
Q: Differentiate function with respect to matrix I need to differentiate the following function:
$$f(\Sigma)=-\frac{1}{2}\log|\Sigma|+-\sum_i C_i\exp\left(-\frac{1}{2}\frac{\mu_i^2}{1+\Sigma_{ii}}\right)$$
to find, $\frac{\partial f}{\partial \Sigma}$. The first term is a standard result. However its the sum of exponential terms that I'm unsure of. Treat $\mu_i, C_i$ to be constants and $\Sigma_{ii}$ are the diagonal terms in $\Sigma$.
I was thinking rewrite the second term as trace of $EC$ where $E$'s diagonal terms containing the exponential terms and $C$ is a diagonal matrix containing the $C_i$'s. <- just a suggestion, not sure if it will lead to a solution.

A: The derivative of the function $f_{ii}(\Delta) = [\Delta]_{ii}$ can be computed by noting that $f_{ii}$ is linear and hence is its own derivative, that is
$Df_{ii}(\Delta)(H) = f_{ii}(H) = [H]_{ii} = \operatorname{tr} (E^{ii} H)$.
The derivative of $g(t) = e^{-{1 \over 2} { \mu_i^2 \over 1 + t}}$ is given by
$g'(t) = {\mu_i^2 \over 2(1+t)^2 }e^{-{1 \over 2} { \mu_i^2 \over 1 + t}} $.
Hence the chain rule gives
$D (g \circ f_{ii})(\Sigma)(H) = Dg(f_{ii}(\Sigma))(Df_{ii}(\Sigma)(H)) =
{\mu_i^2 \over 2(1+\operatorname{tr} (E^{ii} \Sigma))^2 }e^{-{1 \over 2} { \mu_i^2 \over 1 + \operatorname{tr} (E^{ii} \Sigma)}} \operatorname{tr} (E^{ii} H)$.


text:
Q: Ruby DevKit compile issues My compass had broken
>compass compile
LoadError on line ["36"] of C: cannot load such file -- zurb-foundation
  C:/Ruby193/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
  C:/Ruby193/lib/ruby/gems/1.9.1/gems/compass-0.12.2/lib/compass/configuration/data.rb:161:in `requi
re'
  C:/www/project/config.rb:2:in `get_binding'
  [...]

so I decided it was time to reinstall Ruby. Downloaded and installed rubyinstaller-1.9.3-p385.exe. It told me to also install the DevKit.
But gem install rdiscount --platform=ruby didn't go so well:
C:/Ruby193/bin/ruby.exe extconf.rb
checking for random()... no
checking for srandom()... no
checking for rand()... yes
checking for srand()... yes
checking size of unsigned long... 4
checking size of unsigned int... 4
creating Makefile

make
generating rdiscount-i386-mingw32.def
compiling basename.c
compiling Csio.c
Csio.c: In function 'Csputc':
Csio.c:14:5: warning: operation on 'iot->size' may be undefined
compiling css.c
css.c: In function 'mkd_css':
css.c:57:6: warning: operation on 'f.size' may be undefined
compiling docheader.c
compiling dumptree.c
dumptree.c: In function 'Pptype':
dumptree.c:23:22: warning: return discards qualifiers from pointer target type
[...]
dumptree.c:37:22: warning: return discards qualifiers from pointer target type
dumptree.c: In function 'pushpfx':
dumptree.c:44:24: warning: operation on 'sp->size' may be undefined
dumptree.c: In function 'dumptree':
dumptree.c:104:5: warning: initialization discards qualifiers from pointer target type
dumptree.c:104:5: warning: initialization discards qualifiers from pointer target type
compiling emmatch.c
emmatch.c: In function 'emfill':
emmatch.c:79:4: warning: operation on 'p->b_text.size' may be undefined
compiling generate.c
generate.c: In function 'push':
generate.c:37:2: warning: operation on 'f->in.size' may be undefined
generate.c: In function 'Qchar':
generate.c:120:9: warning: operation on 'f->Q.size' may be undefined
generate.c:127:5: warning: operation on 'cur->b_text.size' may be undefined
generate.c: In function 'Qem':
generate.c:172:17: warning: operation on 'f->Q.size' may be undefined
generate.c:179:13: warning: operation on 'f->Q.size' may be undefined
generate.c: In function '___mkd_reparse':
generate.c:197:5: warning: operation on 'sub.in.size' may be undefined
generate.c: In function 'puturl':
generate.c:228:6: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:230:6: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:232:6: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:236:6: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:238:6: warning: passing argument 2 of 'Qprintf' discards qualifiers from pointer target type
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: At top level:
generate.c:458:5: warning: initialization discards qualifiers from pointer target type
generate.c:459:5: warning: initialization discards qualifiers from pointer target type
generate.c:460:5: warning: initialization discards qualifiers from pointer target type
generate.c:461:5: warning: initialization discards qualifiers from pointer target type
generate.c: In function 'isautoprefix':
generate.c:473:29: warning: comparison between signed and unsigned integer expressions
generate.c: At top level:
generate.c:497:1: warning: initialization discards qualifiers from pointer target type
[...]
generate.c:514:5: warning: initialization discards qualifiers from pointer target type
generate.c: In function 'pseudo':
generate.c:527:30: warning: comparison between signed and unsigned integer expressions
generate.c: In function 'p_or_nothing':
generate.c:575:5: warning: return discards qualifiers from pointer target type
generate.c: In function 'extra_linky':
generate.c:594:3: warning: passing argument 2 of 'Qprintf' discards qualifiers from pointer target type
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'linkyformat':
generate.c:632:6: warning: passing argument 2 of 'Qprintf' discards qualifiers from pointer target type
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:633:6: warning: passing argument 2 of 'Qprintf' discards qualifiers from pointer target type
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:637:6: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'cputc':
generate.c:733:5: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:734:5: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:735:5: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'mangle':
generate.c:748:2: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
[...]
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: At top level:
generate.c:1085:5: warning: initialization discards qualifiers from pointer target type
[...]
generate.c: In function 'smartypants':
generate.c:1119:18: warning: comparison between signed and unsigned integer expressions
generate.c:1122:3: warning: passing argument 2 of 'Qprintf' discards qualifiers from pointer target type
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1144:8: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1146:8: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'text':
generate.c:1208:2: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1212:4: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
[...]
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: At top level:
generate.c:1372:1: warning: initialization discards qualifiers from pointer target type
generate.c:1372:1: warning: initialization discards qualifiers from pointer target type
generate.c:1372:1: warning: initialization discards qualifiers from pointer target type
generate.c:1373:7: warning: initialization discards qualifiers from pointer target type
generate.c: In function 'splat':
generate.c:1384:5: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1395:6: warning: passing argument 2 of 'Qprintf' discards qualifiers from pointer target type
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
[...]
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'printblock':
generate.c:1475:5: warning: initialization discards qualifiers from pointer target type
generate.c:1475:5: warning: initialization discards qualifiers from pointer target type
generate.c:1475:5: warning: initialization discards qualifiers from pointer target type
generate.c:1476:5: warning: initialization discards qualifiers from pointer target type
generate.c:1476:5: warning: initialization discards qualifiers from pointer target type
generate.c:1476:5: warning: initialization discards qualifiers from pointer target type
generate.c:1484:3: warning: passing argument 1 of 'push' discards qualifiers from pointer target type
generate.c:34:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1490:7: warning: passing argument 1 of 'push' discards qualifiers from pointer target type
generate.c:34:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'printcode':
generate.c:1507:5: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1519:5: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'htmlify':
generate.c:1546:2: warning: passing argument 2 of 'Qprintf' discards qualifiers from pointer target type
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1551:2: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1555:3: warning: passing argument 2 of 'Qprintf' discards qualifiers from pointer target type
generate.c:155:1: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'definitionlist':
generate.c:1566:2: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1570:3: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1572:3: warning: passing argument 1 of 'Qstring' discards qualifiers from pointer target type
generate.c:135:1: note: expected 'char *' but argument is of type 'const char *'
generate.c:1575:6: warning: passing argument 2 of 'htmlify' discards qualifiers from pointer target type
[...]
cstring.h:73:12: note: expected 'char *' but argument is of type 'const char *'
generate.c: In function 'mkd_document':
generate.c:1710:6: warning: operation on 'p->ctx->out.size' may be undefined
compiling html5.c
html5.c: In function 'mkd_with_html5_tags':
html5.c:15:5: warning: passing argument 1 of 'mkd_define_tag' discards qualifiers from pointer target type
tags.h:17:6: note: expected 'char *' but argument is of type 'const char *'
html5.c:16:5: warning: passing argument 1 of 'mkd_define_tag' discards qualifiers from pointer target type
tags.h:17:6: note: expected 'char *' but argument is of type 'const char *'
html5.c:17:5: warning: passing argument 1 of 'mkd_define_tag' discards qualifiers from pointer target type
tags.h:17:6: note: expected 'char *' but argument is of type 'const char *'
html5.c:18:5: warning: passing argument 1 of 'mkd_define_tag' discards qualifiers from pointer target type
tags.h:17:6: note: expected 'char *' but argument is of type 'const char *'
html5.c:19:5: warning: passing argument 1 of 'mkd_define_tag' discards qualifiers from pointer target type
tags.h:17:6: note: expected 'char *' but argument is of type 'const char *'
html5.c:20:5: warning: passing argument 1 of 'mkd_define_tag' discards qualifiers from pointer target type
tags.h:17:6: note: expected 'char *' but argument is of type 'const char *'
html5.c:21:5: warning: passing argument 1 of 'mkd_define_tag' discards qualifiers from pointer target type
tags.h:17:6: note: expected 'char *' but argument is of type 'const char *'
compiling markdown.c
markdown.c:104:15: warning: initialization discards qualifiers from pointer target type
markdown.c: In function 'quoteblock':
markdown.c:743:17: warning: initialization discards qualifiers from pointer target type
markdown.c:751:12: warning: assignment discards qualifiers from pointer target type
markdown.c: In function 'addfootnote':
markdown.c:955:23: warning: operation on 'f->footnotes->size' may be undefined
markdown.c:963:2: warning: operation on 'foot->tag.size' may be undefined
markdown.c:965:5: warning: operation on 'foot->tag.size' may be undefined
markdown.c:971:6: warning: operation on 'foot->title.size' may be undefined
markdown.c:976:2: warning: operation on 'foot->link.size' may be undefined
markdown.c:977:5: warning: operation on 'foot->link.size' may be undefined
markdown.c:1004:6: warning: operation on 'foot->title.size' may be undefined
markdown.c:1010:2: warning: operation on 'foot->title.size' may be undefined
compiling mkdio.c
mkdio.c: In function 'queue':
mkdio.c:59:3: warning: operation on 'p->text.size' may be undefined
mkdio.c:63:6: warning: operation on 'p->text.size' may be undefined
mkdio.c:67:5: warning: operation on 'p->text.size' may be undefined
mkdio.c: In function 'populate':
mkdio.c:113:6: warning: operation on 'line.size' may be undefined
mkdio.c: In function 'mkd_line':
mkdio.c:275:2: warning: operation on 'f.out.size' may be undefined
compiling rdiscount.c
In file included from c:\ruby193\devkit\mingw\bin\../lib/gcc/mingw32/4.5.2/../../../../include/windows.h:48:0,
                 from c:\ruby193\devkit\mingw\bin\../lib/gcc/mingw32/4.5.2/../../../../include/winsock2.h:22,
                 from c:/Ruby193/include/ruby-1.9.1/ruby/win32.h:40,
                 from c:/Ruby193/include/ruby-1.9.1/ruby/defines.h:223,
                 from c:/Ruby193/include/ruby-1.9.1/ruby/ruby.h:67,
                 from c:/Ruby193/include/ruby-1.9.1/ruby.h:32,
                 from rdiscount.c:2:
c:\ruby193\devkit\mingw\bin\../lib/gcc/mingw32/4.5.2/../../../../include/windef.h:229:23: error: duplicate 'unsigned'
c:\ruby193\devkit\mingw\bin\../lib/gcc/mingw32/4.5.2/../../../../include/windef.h:238:23: error: duplicate 'unsigned'
c:\ruby193\devkit\mingw\bin\../lib/gcc/mingw32/4.5.2/../../../../include/windef.h:238:23: error: two or more data types in declaration specifiers
c:\ruby193\devkit\mingw\bin\../lib/gcc/mingw32/4.5.2/../../../../include/windef.h:241:24: error: duplicate 'unsigned'
rdiscount.c: In function 'rb_rdiscount_to_html':
rdiscount.c:18:5: warning: implicit declaration of function 'rb_rdiscount__get_flags'
rdiscount.c:18:5: warning: ISO C90 forbids mixed declarations and code
rdiscount.c: In function 'rb_rdiscount_toc_content':
rdiscount.c:55:5: warning: ISO C90 forbids mixed declarations and code
make: *** [rdiscount.o] Error 1

I've tried uninstalling Ruby and removing the C:/Ruby193 directory, but the same errors still occurs.
I was hoping that I could just gem install compass and be on my way, but I still get the same error when I run compass compile.
Do you know how to fix this?

A: Looks like there is an issue with the latest version of rdiscount:  https://github.com/rtomayko/rdiscount/issues/74
Try installing the previously tagged version:
gem install rdiscount -v=1.6.8 --platform=ruby


text:
Q: Google Bar Chart custom tooltip does not work This code:
chart = new google.charts.Bar(document.getElementById('chart'));
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', '');
dataTable.addColumn('number', 'Value');
dataTable.addColumn({type: 'string', role: 'tooltip', p: {'html': true}});
var rows = [
    ['U.S.', 2, "tool"],
    ['France', 10, "tip"]
];
dataTable.addRows(rows);
chart.draw(dataTable);

does not result in a custom tooltip.
Strangely it works with other chart types.
Do you know why please?
[edit] Apparently this is not possible. Is there any other way to put a "%" symbol in the tooltip, like in this screenshot?

A: The tooltip should show the formatted value by default.
Using object notation for your values, you can provide a formatted value (f:)
along with the required value (v:)...
you can also use dataTable.setFormattedValue(...) after the table is loaded...
Example...

google.charts.load('current', {
  callback: drawChart,
  packages: ['bar']
});

function drawChart() {
  chart = new google.charts.Bar(document.getElementById('chart'));
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('string', '');
  dataTable.addColumn('number', 'Value');
  var rows = [
      ['U.S.', {v: 2, f: '2%'}],    // add %
      ['France', {v: 10, f: '10%'}],  // add %
      ['Germany', {v: 15, f: 'whatever we want'}]   // add whatever we want
  ];
  dataTable.addRows(rows);
  chart.draw(dataTable);
}


text:
Q: Bokeh can't set axis ticks font axis().major_tick_label_font    ="times"
axis()[0].major_tick_label_font ="times"
axis().major_tick_font          ="times"
xaxis().major_tick_font         ="times"

Nothing worked. How to set the font of the ticks? Not the axis label, but the ticks label.

A: The names of some of the properties are unfortunately a little overly verbose. Text properties all have basic names like text_font_size and then that may also have a prefix like major_label. (In this case, major_label is the "label for a major tick") So all together the proper attribute name is major_label_text_font.
You can see an example that sets similar properties here:
https://docs.bokeh.org/en/latest/docs/user_guide/styling.html#axes
And there is information in the docs about general properties here:
https://docs.bokeh.org/en/latest/docs/user_guide/styling.html


text:
Q: Apache Last-Modified header with now I would like to set the Last-Modified header in Apache so that it will always returns the current date time.
Do you know how and if is possible to achieve that?
Header always set Last-Modified "{now} GTM"

A: You can use an expression with time variables.
For example:
Header always set Last-Modified "expr=%{TIME_YEAR}-%{TIME_MON}-%{TIME_DAY} %{TIME_HOUR}:%{TIME_MIN}:%{TIME_SEC}"

Will add in your response:
last-modified: 2022-08-04 08:12:03


text:
Q: Need help on extracting data using Xpath in my Python code Question 1
Here is the HTML code.

ph:(02) 9540 9959

I am trying to extract that phone number using xpath.
I have tried
data['phone'] = c.xpath('.//span[@preferredContact="40"]/text()')

and
data['phone'] = c.xpath('.//span[contains(@preferredContact,"40")]/text()')

Both of them return only null. Can someone show me the code to extract that phone number, please?
Question 2
HTML code is
<a rel="nofollow" title="View website for Ruth Newman Architect (in new window)" target="_blank" name="listing_website" id="websiteLink40" alreadysentorpevent="false" class="links ext-no-tooltip orpDuplicateEvent" href="/app/redirect?headingCode=27898&productId=473639214&productVersion=1&listingUrl=%2Fnsw%2Fgymea-bay%2Fruth-newman-architect-12781682-listing.html&webSite=http%3A%2F%2Fwww.ruthnewman.com.au&pt=w&context=businessTypeSearch&referredBy=YOL&eventType=websiteReferral">www.ruthnewman.com.au

I want to get the link which is located next to the string webSite=http%3A%2F%2F. This string is in the href attribute's value. So, in the above example, I want www.ruthnewman.com.au. I do not know how to get that using Xpath.
Can someone help out please?

A: Attributes are case-sensitive. For the first question use (no caps):
.//span[@preferredcontact='40']/text()

For the second question use:
substring-before(substring-after(
    .//a[contains(@href, 'webSite=')]/@href, 'webSite=http%3A%2F%2F'), '&')

This first selects everything after 'webSite=http%3A%2F%2F' in the attribute, then, using that as the input to substring-before, extracts everything before the first &, which should contain the target string.
Note that in your given examples the descendant-or-self (//) axis is not really needed. Try to avoid it whenever possible. The flexibility gained comes at the cost of precision and efficiency.


text:
Q: Is the SMTP virtual server deprecated in IIS 7? It seems that in IIS 7 (7.5, Windows Server 2008 R2) the SMTP virtual server is a second-class citizen, only being configurable through the IIS 6.0 compatibility-mode management tool. This arrangement leads me to wonder whether the SMTP virtual server is deprecated, or otherwise "on it's way out".
Is this accurate? Is the SMTP virtual server shipped with IIS being phased out? Is there a replacement on its way in?

A: TL;DR from here: Yes, it's gone. You can install IIS 6 SMTP server, but it sucks. Far better to use something like hMailServer which is free and works great.

A: It is recently that Microsoft started to add explicit notes to its documentation around IIS 6 SMTP service in recent Windows releases (IIS 8 and above) that deprecating this component for good,

The IIS SMTP Virtual Server Component that is mentioned in this article is part of IIS 6.0, the support for which has ended with the support of Windows Server 2003. To relay emails to Office 365, use one of the supported versions of Exchange Server.

https://learn.microsoft.com/en-us/iis/application-frameworks/install-and-configure-php-on-iis/configure-smtp-e-mail-in-iis-7-and-above#note
So literally speaking, you shouldn't use SMTP service after July 14, 2015 (end of life date for Windows Server 2003).


text:
Q: Pardot CustomField array - not being updated by x-www-form-urlencoded POST API I have a Prospect object in Pardot containing the following multi-select field:
"Your_Interests": {
                "value": [
                  "Option1",
                  "Option2",
                  "Option3"
                ]
              }

(This is at least what I get when pulling the data from the prospect using the API endpoint: https://pi.pardot.com/api/prospect/version/4/do/read/email/{{email}}?format=json)
I am trying to update the prospect, using the API:
https://pi.pardot.com/api/prospect/version/4/do/upsert/id/{{ID}}?format=json
Whose Content-Type is application/x-www-form-urlencoded.
The raw payload / parameters work well when it comes to updating free text fields, such as:
first_name=John&last_name=Doe
But I struggle with update the Your_Interests field (or any similar fields with multiple values)
I have been trying many syntaxes:
Your_Interests.value[0]=Option4

Your_Interests.value[]=Option4

Your_Interests[0]=Option4

Your_Interests[]=Option4

Your_Interests[value][0]=Option4

Your_Interests[value][]=Option4

Your_Interests.value[0]=Option4

Your_Interests=[Option4]

Your_Interests.value=[Option4]

Your_Interests[value]=[Option4]

But no luck. I am not using / cannot use postman - I'm using a built-in workflow builder of a home made platform, thus the field where I'd input the payload/parameter is just a text box - I don't believe I need to manually URL encode special character, the builder should do it on its own when sending the API call.
How would you update this type of values?
Thanks!

A: Your best bet is to use PostMan driving the API so that you can learn exactly how the Pardot API is expecting to see the values passed to it. Once that's figured out, you can take the approach and apply it to your code.
Consider focusing on the following attempts:

*

*Your_Interests[]=Option1

*Your_Interests[]=Option2

or (I'm less confident in this approach)

*

*Your_Interests=Option1;Option2

Hopefully this gives you enough to get on the right track.


text:
Q: Delivering report for push notification in iOS Currently I am working on a chat based app using socket. In android it works fine since android has no restriction in working with socket in background. I searched a lot about running socket in iOS in background. iOS is very strict in that case. So that I found sending push notification from server is good instead of sending from socket. But I want to send delivery reports of messages whenever I received a push without opening the app.
Is there any way to do that? If I can't send emit socket, it's ok. Can I send a server call at least?
Thanks in advance.

A: Now in iOS 10 and iOS 11, you should be using PushKit for handling push notifications for incoming Voice over IP calls. So when you build your app against the iOS 10/11 SDK, you need to move over to PushKit (which can be supported all the way back to iOS 8, but once you move to iOS 10/11 the recommendation is to update your minimum deployment target to iOS 9).
// Link to the PushKit framework
import PushKit

// Trigger VoIP registration on launch
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    self.voipRegistration()
    return true
}

// Register for VoIP notifications
func voipRegistration {
    let mainQueue = dispatch_get_main_queue()

    // Create a push registry object
    let voipRegistry: PKPushRegistry = PKPushRegistry(mainQueue)

    // Set the registry's delegate to self
    voipRegistry.delegate = self

    // Set the push type to VoIP
    voipRegistry.desiredPushTypes = [PKPushTypeVoIP]
}


text:
Q: Is there any solution to handle Transactional by defining in Abstract Class of Concrete Method? I am defining Transaction function in my application, But its not working for Abstract class of Concrete method, Since my controller is calling first Abstract class method then it will enter to Concrete class method. Can anyone help me to fix? I tried with Concrete class method, its working, But I need to bring it to abstract layer since I am calling CRUD Operation DAO function in Abstract layer only.
I tried to insert data for Multiple table and at last I thrown exception to make sure Transaction has to roll back. But Data is capturing even though Exception occurs also.
 --Controller code Start
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String add() throws Exception {

    addDTO();
    return "demo";

}

protected void addDTO() {

    try {
        service.addDTO();
    } catch (Exception e) {
        log.error("addDTO", e);
    }
}

 --- Controller code End

 --- Abstract Service with concrete method
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
public void addDTO() throws Exception {
    try {

        E entity = this.entityFromDTO();
        this.dao.add(entity);

        // Added For Transaction Test START
        TMstPackage packType = getPackageEntity();
        mstPackageDao.add(packType);

        throw new Exception("Transaction RollBack test");

        // Added For Transaction Test END

    } catch (Exception ex) {
        Log.error("addData");
        throw ex;
    }

}

 --- Concrete Service
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { Exception.class })
protected TMstContainer entityFromDTO() throws Exception {

    TMstContainer container = null;
    try {
        Date date = Calendar.getInstance().getTime();
        container = new TMstContainer();
        container.setCntCode("TEST1");
        container.setCntDescription("Test Desc");

        container.setCntDtCreate(date);
        container.setCntDtLupd(date);
        container.setCntStatus('A');
        container.setCntUidCreate("SYS");
        container.setCntUidLupd("SYS");

    } catch (Exception e) {
        log.error(e);
    }
     return container;
}

The same code I tried by defining in concrete class function with @Transactional, Its working Fine. But If I bring it to abstract function with same annotation, Data is capturing to database.Can anyone please help.
Image for Abstract Class with Concrete method & @Transactional annotation defined :

A: This is the expected behavior. @Transactional method should be directly called from outside, in that case the object instance should be retrieved through spring injection.
Spring doesn't do any magic here. it creates a AOP proxy fro the class you specified, and if someone call a method using that proxy , if the method is annotated as @Transactional , that proxy method invocation handler will execute it through a transaction template.
if you call a Transnational method directly from a non transnational method in that class, spring doesn't know anything.


text:
Q: Strange behaviour of PHP DateTime Class I'm trying to get the time difference in milliseconds.
$_SESSION['startTime'] = time();
$to_time = time();

//I call the code from here after a delay, say 4 seconds

$from_time = $_SESSION['startTime'];
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);

print_r( $d1->diff($d2));

I print the result after 4 seconds and the result is somewhat like this:
DateInterval Object
(
    [y] => 4 //---- Problem, this value should be +
    [m] => 0 //                                   |
    [d] => 0 //                                   |
    [h] => 0 //                                   |
    [i] => 0 //                                   |
    [s] => 0 //<-here-----------------------------+
    [invert] => 1
    [days] => 1461
)

[s] should have been 4. why the 4 is in the year section?
What am I doing wrong?
UPDATE - Solved
$to_time = (microtime(true));
$from_time = ( $_SESSION['startTime']);
$diff = $to_time - $from_time;
print $diff;

Prints
3.xxxxxx

A: You must specify the formatting. You're sending in a unix timestamp into DateTime, therefor:
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);

Becomes
$d1 = new DateTime('@'.$from_time);
$d2 = new DateTime('@'.$to_time);

The @ symbol tells DateTime that I'm using a Unix Timestamp.

A: The constructor for DateTime accepts a string as a parameter not a timestamp, which is why you are seeing the "strange behaviour".
You need to expressly set the timestamp after insantiating a DateTime object:-
$from_time = $_SESSION['startTime'];
$d1 = new DateTime();
$d1->setTimestamp($from_time);


text:
Q: PHP 5.3.5 fileinfo() MIME Type for MS Office 2007 files - magic.mime updates? On a PHP upload, I'm trying to validate the MIME Type of the files being uploaded to match a valid set of MIME types for the application.  When attempting to use the fileinfo() to determine the MIME type of an Office 2007 file it is NOT detecting as their appropriate MIME Types.  Instead the MIME type response is "application/zip"
Office Document MIME types:
http://filext.com/faq/office_mime_types.php
Example PHP Code:

$oFileInfo = new finfo( FILEINFO_MIME_TYPE );
$sMimeType = $oFileInfo -> file( $_FILES['Filedata']['tmp_name'] );
echo $sMimeType;

Server Setup Info:

*

*OS:  Windows Server 2003 32-bit

*Webserver: IIS 6.0

*PHP: 5.3.5 (Thread Safe) using FastCGI 1.5

*File: magic.mime

*

*Example by darko at uvcms dot com 16-Apr-2008 09:35

*

*Link: php.net/manual/en/fileinfo.installation.php

*Size: 517 KB

*Source: Source Forge: GNU32 - FileType gnuwin32.sourceforge.net/packages/filetype.htm

I've found numerous posts which refer to issues with the newer Office format when downloading from a webserver.  In all these examples I haven't found anywhere that illustrates a manor of adding the new MIME types to an existing magic.mime file, or a link to a magic.mime file that already contains the Microsoft Office 2007+ MIME types.  Thanks for your assistance.

A: Newer Office files are actually ZIP archives. That's why MIME Magic database is detecting them as ZIP files. You may need to add special rules based on file extension, or look into the ZIP file to see if it has a docProps folder (Office ZIP archives have such a folder containing meta data about the document).
There are other file formats which are actually ZIP archives with a different extension, e.g. JAR files.

A:

*

*Yes, you should update magic.mime.

lol, yeah, just update it, problem solved.
Unfortunately, it looks like the magic mime type systems works off of looking at the actual file contents, and because the file is compressed, it can't uncompress (and look at which file?)
someone suggested writing a function to unzip compressed files and then checking for the existence of a "DocProps" directory, for instance. But this would introduce another vector of attack to the production server.

A: *

*Yes, you should update magic.mime.

*Thumb up for not believing mime type sent from browser ($_FILES['Filedata']['type'])

*Why you are using a function that the manual said it's deprecated? http://php.net/manual/en/function.mime-content-type.php
Note: finfo() determine the MIME type of a file by it's magic bytes; given the fact that Office 2007 files (and many other file formats, e.g. ePUB) are simply zip packages with specified directory structure, it's reasonable to have finfo() to return application/zip.
I would suggest unzip or list the content to inspect it's structure, if you really want to determinate the file type based on it's content (and not the MIME type browser reports when uploading)

A: Have you tried to add the new mime types to IIS ?

*

*Get to the Internet Management snap-in

*Right click "Web Sites" and select "Properties"

*Select "HTTP Headers"

*Select "Mime Types"

*Enter a new extension with no leading period and the appropriate mime type. Repeat as needed for each extension.

*Click "OK" to close all the dialogs


text:
Q: What (more elegant) methods exist to parse discrete chunks of data as if they were one? I have a problem:  I will be getting data from an external source.  I will be getting this data in chunks, unfortunately.
The function, in psuedocode, looks like this:
stringy chunk;

recievedata(stringy incomingdata,number size_of_incoming_data){

chunk=malloc(size_of_incoming_data)
chunk=incomingdata
}

However, the incoming data is a string an must be parsed thoroughly, and there is a significant chance that target words of the data will be split across chunks in a non-predictable fashion.  This function is called by the curl library of OpenSSL, for the record, several times to pass data that is being received.
As it stands in pusedocode above, this will just keep overriding the old data.  I could fix this using a buffer, such as:
    stringy chunk;
    stringy buffer;

    recievedata(stringy incomingdata,number size_of_incoming_data){

    if (chunk is assigned) {
      buffer = chunk;
      chunk=malloc(size_of_incoming_data+size_of_old_data)
      chunk = buffer + incomingdata
      free (buffer)
    }
    }

Alas, this seems kind of horrible. I find it extremely ugly that I have two have two copies of the same data for no functional reason.  Because this is something of a deamon running a machine that has other things to do, I need to be as conservative as possible with resources such as memory.
Would anyone be so kind as to enlighten me as to the most efficient methods that are available for handling data in this manner?
Thank you.

A: The customary way to work with data chunks is to build a higher level interface that treats them as a stream. For example, you might have
     char nextByteInStream () ;

to get a single byte (omitting error handling parameters). Or
     void nextBytes (char *, int count) ;

to return a a number of bytes.
In compression, it is common to have something like:
    unsigned int nextBits (int count) ;

returning one or more bits in a stream.
Use such an interface to isolate the inherent messiness of chunk data.

A: // the following assumes no 0x00 bytes in data
// if there are 0x00 bytes, then track current size of used memory
// and use memcpy() to put incoming data into data at next available byte
// (remembering to update the index to the next available byte in the
// allocated memory

char *data = malloc(1);
*data = '\0';
char *temp = NULL;

recievedata(stringy incomingdata,number size_of_incoming_data)
{
    temp = realloc( data, strlen(data)+size_of_incoming_data  );
    if( NULL != temp )
    { // then successful realloc
         data = temp;
         strncat( data, incomingdata, size_of_incoming_data );
    }
    else
    { // handle realloc error
}

A: As @Paul says in the comments, this is very common producer-consumer buffering problem.  The receivedata callback is the producer.  The parser is the consumer.  The buffer is the communication channel between them.  It has a fill pointer to show end of current data.
Each time receivedata runs,

*

*Concatenate the new data to what's already there (by copying to the fill pointer location) and advance the fill pointer.

*Run the parser to consume as many complete words (your term) as possible.  Parsing of the last word may fail because it's not complete.

*Copy any the incomplete word to the start of the buffer. And set the fill pointer adjusted to its end.

In C:
char *buf = NULL;
size_t fill_ptr = 0, buf_size = 0;

static void expand_buffer_to(size_t size) {
  if (size < buf_size) {
    buf = realloc(buf, size);
    if (buf == NULL) handle_realloc_fail();
    buf_size = size;
  }
}

void receivedata(char *incoming_data, size_t size_of_incoming_data) {

  // Make sure the buffer is big enough to accept new data.
  expand_buffer_to(fill_ptr + size_of_incoming_data);

  // Concatenate to end of buffer.
  memcpy(buf + fill_ptr, incoming_data, size_of_incoming_data);

  // Adjust fill pointer to include new data.
  fill_ptr += size_of_incoming_data;

  // Run the parser. fill_ptr is input size.
  // Return number of characters parsed successfully.
  size_t n_chars_parsed = parse_words(buf, fill_ptr);

  // Move any incomplete word chars (maybe 0) to the start of the buffer.
  memmove(buf, buf + n_chars_parsed, fill_ptr - n_chars_parsed);

  // Move fill pointer to end of incomplete word.
  fill_ptr -= n_chars_parsed;
}

This is more-or-less how all I/O of variable length records works.  NB some have talked about the stream abstraction, and this is a nice way to go if character-by-character handling is desired.  However IME introducing a character stream abstraction tends toward code with more layers of copying and buffering than is really needed.  By passing the parser a buffer load of data at a time as above, it's easier to avoid that.  Of course if your application is not performance critical, it won't make any difference.