text:
Q: c openmp - parallelization of a while loop I would like to parallelize a while loop in C with OpenMP. It is a classic while until flag = false.
This is a semi-pseudo-code of my work without openMP
//Something before
found = 0;
while (!found){
  //Pull an element from an array and do some work with it
  if(something) found = 1;
  //Do other work and put an element in the same array
}
//Something later

It is not a problem for me if the work in the loop is done some times more, it's just overwork that doesn't affect the results. There is a simple correct way to parallelize this with OpenMP in C?
Thanks
As requested, this is the complete code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>

typedef struct location {int x, y;} location;

typedef struct node {
    int x, y;               // Coordinates of the node on the grid
    int x_prec, y_prec;     // Coordinates of the predecessor
    int walkable;           // Whether this node can be walked through
    int opened;             // It indicates if the node was been estimated
    int closed;             // It indicates if the node was been evaluated
    int inPath;             // If the node is in the shortest path
    int g;                  /* The past-cost function, which is the known distance from the starting
                             * node to the current one. */
    int f;                  /* The estimated-cost function, which is an admissible heuristic estimate
                             * of the distance from the starting node to the goal passing through the
                             * current node. */
    int h;                  // The estimated cost of the path between the current node and the goal
} node;

typedef struct list {
    location loc;
    int isValid;
} list;

location start,end;
node **grid;
int cols, rows;

double time1, time2, time3, time4, time5;
double time_aStar_s, time_aStar_e;
double time_getNeighbor_s, time_getNeighbor_e;
double time_while_s, time_while_e;
double time_for_s, time_for_e;
double time_for = 0;
double time_pull_s, time_pull_e;
double time_pull = 0;
int count_getNeighbor = 0;
int count_current = 0;

void setGrid(char [6]);

int checkLocation(location);

void aStar(int);

int isListEmpty(list *);

void constructPath(location);

void getNeighbor(location, location *);

int heuristic(location, location);

void printStatistics();

void saveStatistics(char *);

int main (int argc, char *argv[]){
    char input_map[20];
    int input_algo = -1;
    char input_stat[20];

    printf("Which map you prefer?\n");
    scanf("%s", input_map);
    setGrid(input_map);
    printf("Enter a valid start point.\n");
    scanf("%i", &start.x);
    scanf("%i", &start.y);
    printf("Enter a valid end point.\n");
    scanf("%i", &end.x);
    scanf("%i", &end.y);
    if (checkLocation(start) || checkLocation(end)) printf("Invalid start and/or end points.\n");
    printf("Dijkstra or A*?(press <0> or <1> respectively)\n");
    scanf("%i", &input_algo);

    // Save when aStar is called
    time_aStar_s = omp_get_wtime();

    if(input_algo == 0) aStar(0);           // 0 for Dijkstra
    else if (input_algo == 1) aStar(1);         // 1 for A*

    // Save when aStar finishes
    time_aStar_e = omp_get_wtime();

    printf("End of the program. \n");
    printStatistics();
    printf("Would you like to save the statistics?(Enter <y> or <n> respectively)\n");
    scanf("%s", input_stat);
    if(input_stat[0] == 'y'){
        printf("Enter file name.\n");
        scanf("%s", input_stat);
        saveStatistics(input_stat);
    }
    return(0);
}

void setGrid(char mapName[6]) {
    char temp[1024];
    char fileName[20];
    int i,j;
    FILE *file;

    // Try to open the file
    strcpy(fileName, "src/maps/");
    strcat(fileName, mapName);
    if((file = fopen(fileName, "r")) == NULL){
        printf("ERROR: No such file.\n");
        exit(1);
    }

    // Save dimensions of the map
    rows = 0;
    while(42){
        if(fscanf(file, "%s", temp) == EOF){
            printf("EOF\n");
            printf("columns: \t%i \nrows: \t\t%i\n", cols, rows);
            break;
        }
        printf("%s\n", temp);
        cols = strlen(temp);
        rows++;
    }

    // Reset the file position indicator
    rewind(file);

    // Set dimensions of grid matrix
    grid = (node **)malloc(rows * sizeof(node*));
    for(i = 0; i < rows; i++) grid[i] = (node *)malloc(cols * sizeof(node));

    i=0;
    while(42){
        if(fscanf(file, "%s", temp) == EOF) break;
        for (j = 0; j < cols; j++) {
            grid[i][j].x = i;
            grid[i][j].y = j;
            grid[i][j].x_prec = -1;
            grid[i][j].y_prec = -1;
            if(temp[j] == '#') {
                grid[i][j].walkable = 0;
            } else if(temp[j] == '-') {
                grid[i][j].walkable = 1;
            }
            grid[i][j].opened = 0;
            grid[i][j].closed = 0;
            grid[i][j].inPath = 0;
            grid[i][j].g = -1;
            grid[i][j].f = -1;
        }
        i++;
    }
    fclose(file);
}

void printGrid(int option) {
    int i,j;

    switch(option){
    case 0:
        // It prints grid with start point, end point and optimal path
        for(i = 0; i < rows; i++) {
            for(j = 0; j < cols; j++) {
                if(i == start.x && j == start.y) printf("S");
                else if(i == end.x && j == end.y) printf("E");
                else if (grid[i][j].walkable){
                    if (grid[i][j].inPath) printf("+");
                    else printf(" ");
                } else printf("#");
            }
            printf("\n");
        }
        printf("\n");
        break;
    case 1:
        // It prints evaluated cost g
        for(i = 0; i < rows; i++) {
            for(j = 0; j < cols; j++) {
                if (grid[i][j].walkable){
                    if(grid[i][j].closed == 1) printf("%3d ", grid[i][j].g);
                    else printf("    ");
                } else printf("### ");
            }
            printf("\n");
        }
        printf("\n");
        break;
    case 2:
        // It prints estimated cost g
        for(i = 0; i < rows; i++) {
            for(j = 0; j < cols; j++) {
                if (grid[i][j].walkable){
                    if(grid[i][j].closed == 1) printf("%3d ", grid[i][j].g);
                    else printf("    ");
                } else printf("### ");
            }
            printf("\n");
        }
        printf("\n");
        break;
    default:
        printf("ERROR: Bad option %i for function printGrid(). Please check the code.\n", option);
        break;
    }
}

int checkLocation(location l) {
    if(grid[l.x][l.y].walkable) return(0);
    else return (1);
}

void aStar(int opt_dijkstra) {

    list openList[10000];
    location current;
    location neighbors[4];
    int empty;
    int found = 0;

    int i,j;    // Counters
    int exit;   // control variable
    int f_min;
    int pos;
    int x,y;
    int ng;

    // Set g and f values of the start node to be 0
    grid[start.x][start.y].g = 0;
    grid[start.x][start.y].f = 0;

    // Initialization of the open list
    for (i = 0; i < sizeof(openList)/sizeof(openList[0]); i++) {
        openList[i].isValid = 0;
    }

    // Push the start node into the open list
    grid[start.x][start.y].opened = 1;
    openList[0].loc.x = start.x;
    openList[0].loc.y = start.y;
    openList[0].isValid = 1;

    // Save when the "while is not empty" begins
    time1 = time_while_s = omp_get_wtime();

    // While the open list is not empty
    empty = isListEmpty(openList);

    while (!empty && !found){

        // Save time to pull a node
        time_pull_s = omp_get_wtime();

        // pull the position of the node which has the minimum f value
        f_min = -1;
#pragma omp parallel for default(none) shared(openList, f_min, current, pos, grid)
        for(i = 0; i < sizeof(openList)/sizeof(openList[0]); i++) {
            if (openList[i].isValid == 1 && (f_min == -1 || (grid[openList[i].loc.x][openList[i].loc.y].f < f_min))){
#pragma omp critical(pullopenlist)
                {
                f_min = grid[openList[i].loc.x][openList[i].loc.y].f;
                current.x = openList[i].loc.x;
                current.y = openList[i].loc.y;
                pos = i;
                }
            }
        }
        openList[pos].isValid = 0;
        grid[current.x][current.y].closed = 1;

        //Save time to pull a node
        time_pull_e = omp_get_wtime();
        time_pull += time_pull_e - time_pull_s;

        // Update the count of evaluated points
        count_current++;

        // If the end position is reached, construct the path and return it
        if (current.x == end.x && current.y == end.y){
            printf("Reached the end position.\n");
            constructPath(end);     // To be defined
            found = 1;
        }

        // Save when enter in getNeighbor
        time_getNeighbor_s = omp_get_wtime();

        // Get neighbors
        getNeighbor(current, neighbors);

        // Save when exit from getNeigbor
        time_getNeighbor_e = omp_get_wtime();

        // Get the distance between current node and the neighbor and calculate the next g score
        ng = grid[current.x][current.y].g + 1;

        // Save when started the "for all neighbors"
        time2 = time_for_s = omp_get_wtime();

        // Evaluate neighbors
        /* Seems that is not convenient to parallelize the loop.
         * Probably this happens because of critical section
         */
#pragma omp parallel for default(none) private(x, y, j) shared(exit, openList, neighbors, ng, grid, opt_dijkstra, end, current)
        for (i = 0; i < 4; i++) {
            x = neighbors[i].x;
            y = neighbors[i].y;

            if (x != -1 || y != -1){
                // Check if the neighbor has not been inspected yet, or if it
                // can be reached with smaller cost from the current node
                if (!grid[x][y].opened || ng < grid[x][y].g) {
                    grid[x][y].g = ng;
                    if(opt_dijkstra == 0) grid[x][y].h = 0;     // Dijkstra case with heuristic cost = 0;
                    else grid[x][y].h = heuristic(neighbors[i], end);
                    grid[x][y].f = grid[x][y].g + grid[x][y].h;
                    grid[x][y].x_prec = current.x;
                    grid[x][y].y_prec = current.y;
                }

                // If the neighbor is not in open list push it into it
#pragma omp critical (pushopenList)
                {
                    if(!grid[x][y].opened) {
                        exit = 0;
                        for(j = 0; exit == 0; j++) {
                            if(openList[j].isValid == 0) {
                                openList[j].loc.x = x;
                                openList[j].loc.y = y;
                                openList[j].isValid = 1;
                                exit = 1;
                            }
                        }
                    }
                    grid[x][y].opened = 1;
                }
            }
        }

        // Save when finish the "for all neighbors"
        time_for_e = omp_get_wtime();
        time_for += time_for_e - time_for_s;
    } // End while the open list is not empty until end point is found.

    // Save when finish the "while is not empty"
    time_while_e = omp_get_wtime();
}

int isListEmpty(list l[]){
    // It should check if the list is empty. It checks if there is at least one element that is valid.
    int i;
    int empty = 0;
    for (i = 0; i < sizeof(l)/sizeof(l[0]); i++){
        if (l[i].isValid){
            empty = 1;
            i = sizeof(l)/sizeof(l[0]);
        }
    }
    return (empty);
}

void constructPath(location n){
    /* The function reconstructs the path starting from the given point setting .inPath
     */
    int i;
    location temp;
    location temp_prec;

    temp.x = grid[n.x][n.y].x;
    temp.y = grid[n.x][n.y].y;
    grid[temp.x][temp.y].inPath = 1;

    for(i = 0; grid[temp.x][temp.y].x_prec != -1; i++) {
        temp_prec.x = grid[temp.x][temp.y].x_prec;
        temp_prec.y = grid[temp.x][temp.y].y_prec;
        temp.x = temp_prec.x;
        temp.y = temp_prec.y;
        grid[temp.x][temp.y].inPath = 1;
    }
}

void getNeighbor(location current, location neighbors[4]){
    /*
     * Get the neighbors of the given node.
     *
     *    offsets
     * +---+---+---+
     * |   | 0 |   |
     * +---+---+---+
     * | 3 |   | 1 |
     * +---+---+---+
     * |   | 2 |   |
     * +---+---+---+
     */
    int i;
    int x = current.x;
    int y = current.y;

    // Update count of getNeighbor executions
    count_getNeighbor++;

    for (i = 0; i < 4; i++){
        switch(i) {
        // ↑
        case 0:
            if(x >= 0 && y - 1 >= 0 && x < rows && y - 1 < cols && grid[x][y - 1].walkable){
                neighbors[i].x = x;
                neighbors[i].y = y - 1;
            } else{
                neighbors[i].x = -1;
                neighbors[i].y = -1;
            }
            break;
            // →
        case 1:
            if(x + 1 >= 0 && y >= 0 && x + 1 < rows && y < cols && grid[x +1][y].walkable){
                neighbors[i].x = x + 1;
                neighbors[i].y = y;
            } else{
                neighbors[i].x = -1;
                neighbors[i].y = -1;
            }
            break;
            // ↓
        case 2:
            if(x >= 0 && y + 1 >= 0 && x < rows && y + 1 < cols && grid[x][y + 1].walkable) {
                neighbors[i].x = x;
                neighbors[i].y = y + 1;
            } else{
                neighbors[i].x = -1;
                neighbors[i].y = -1;
            }           break;
            // ←
        case 3:
            if(x - 1 >= 0 && y >= 0 && x - 1 < rows && y < cols && grid[x - 1][y].walkable) {
                neighbors[i].x = x - 1;
                neighbors[i].y = y;
            } else{
                neighbors[i].x = -1;
                neighbors[i].y = -1;
            }
            break;
        }
    }
}

int heuristic(location from, location to){
    int h;
    // Manhattan distance from the two points
    h = abs(from.x - to.x) + abs(from.y - to.y);
    return(h);
}

void printStatistics(){
    // Print some useful statistics about the parallel execution of the program
    printf("\nStatistics of aStar:\n");
    printf("time to execute aStar: \t\t\t\t%f \tms\n", 1000*(time_aStar_e - time_aStar_s));
    printf("time at first check point: \t\t\t%f \tms\n", 1000*(time1 - time_aStar_s));
    printf("time at second check point: \t\t\t%f \tms\n", 1000*(time2 - time_aStar_s));

    printf("\nStatistic of \"while until is empty\":\n");
    printf("number of iterations: \t\t\t\t%i\n", count_current);
    printf("mean time to do an iteration: \t\t\t%f \tms\n", 1000*(time_while_e - time_while_s)/count_current);
    printf("time to do all iterations: \t\t\t%f \tms\n", 1000*(time_while_e - time_while_s));

    printf("\nStatistic of pull a node into openList:\n");
    printf("mean time to perform a pull operation: \t\t%f \tms\n", 1000*time_pull/count_current);
    printf("total time spent to perform pulls operations: \t%f \tms\n", 1000*time_pull);

    printf("\nStatistic of \"for each neighbor\":\n");
    printf("total number of iterations: \t\t\t%i\n", 4*count_current);
    printf("mean time to do all four iterations: \t\t%f \tms\n", 1000*time_for/count_current);
    printf("time to do the last four iterations: \t\t%f \tms\n", 1000*(time_for_e - time_for_s));
    printf("time to do all the iterations: \t\t\t%f \tms\n", 1000*time_for);

    printf("\nStatistic of getNeighbor:\n");
    // time_getNeighbor is updated at each execution, so we have only the value relative to the last execution
    printf("time to execute getNeighbor (last execution): \t%f \tms\n", 1000*(time_getNeighbor_e - time_getNeighbor_s));
    printf("number of executions: \t\t\t\t%i\n", count_getNeighbor);
    // Just an indicative time, it is NOT the time to do all executions
    printf("estimated time to do all executions: \t\t%f \tms\n", 1000*count_getNeighbor*(time_getNeighbor_e - time_getNeighbor_s));
}

void saveStatistics(char *string_input){
    FILE *fileOutput;
    char fileOutputName[30];

    strcpy(fileOutputName, "src/stats/");
    strcat(fileOutputName, string_input);
    if((fileOutput = fopen(fileOutputName, "w")) == NULL){
        printf("ERROR: Error in opening the output file.\n");
        exit(1);
    }

    // Print some useful statistics about the parallel execution of the program
    fprintf(fileOutput, "\nStatistics of aStar:\n");
    fprintf(fileOutput, "time to execute aStar: \t\t\t\t%f \tms\n", 1000*(time_aStar_e - time_aStar_s));
    fprintf(fileOutput, "time at first check point: \t\t\t%f \tms\n", 1000*(time1 - time_aStar_s));
    fprintf(fileOutput, "time at second check point: \t\t\t%f \tms\n", 1000*(time2 - time_aStar_s));

    fprintf(fileOutput, "\nStatistic of \"while until is empty\":\n");
    fprintf(fileOutput, "number of iterations: \t\t\t\t%i\n", count_current);
    fprintf(fileOutput, "mean time to do an iteration: \t\t\t%f \tms\n", 1000*(time_while_e - time_while_s)/count_current);
    fprintf(fileOutput, "time to do all iterations: \t\t\t%f \tms\n", 1000*(time_while_e - time_while_s));

    fprintf(fileOutput, "\nStatistic of pull a node into openList:\n");
    fprintf(fileOutput, "mean time to perform a pull operation: \t\t%f \tms\n", 1000*time_pull/count_current);
    fprintf(fileOutput, "total time spent to perform pulls operations: \t%f \tms\n", 1000*time_pull);

    fprintf(fileOutput, "\nStatistic of \"for each neighbor\":\n");
    fprintf(fileOutput, "total number of iterations: \t\t\t%i\n", 4*count_current);
    fprintf(fileOutput, "mean time to do all four iterations: \t\t%f \tms\n", 1000*time_for/count_current);
    fprintf(fileOutput, "time to do the last four iterations: \t\t%f \tms\n", 1000*(time_for_e - time_for_s));
    fprintf(fileOutput, "time to do all the iterations: \t\t\t%f \tms\n", 1000*time_for);

    fprintf(fileOutput, "\nStatistic of getNeighbor:\n");
    // time_getNeighbor is updated at each execution, so we have only the value relative to the last execution
    fprintf(fileOutput, "time to execute getNeighbor (last execution): \t%f \tms\n", 1000*(time_getNeighbor_e - time_getNeighbor_s));
    fprintf(fileOutput, "number of executions: \t\t\t\t%i\n", count_getNeighbor);
    // Just an indicative time, it is NOT the time to do all executions
    fprintf(fileOutput, "estimated time to do all executions: \t\t%f \tms\n", 1000*count_getNeighbor*(time_getNeighbor_e - time_getNeighbor_s));

    fclose(fileOutput);

    printf("Saved all the stats");
}

If you have suggestion on the other parts of code you're welcome.

A: You can certainly do something like this with OpenMP, but it isn't as simple as putting #pragma omp parallel around a for loop.  For that structure, the compiler needs to know at the time of entering the loop how many iterations will be made, so that it can decompose the iterations across threads; and you necessarily don't have that information here when you're exiting once you've found something.
You can make something like this work  - and it can be very useful if the test you need to perform is very CPU heavy (here, I have a made-up example of brute-force primality testing), so that you're breaking up the work amongst several cores, and you only care about finding a result (or that there are none).  But note that you are definitely not guaranteed that doing this in parallel will return the first result.
In the below example, we have a flag found that is set (using an omp atomic capture construct) when a thread finds an item.  If it was the first to set the flag, it stores the value and location.  Once the threads (eventually) see the flag has been set, they all return from the while loop.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "omp.h"

/* brute force prime-testing algorithm */
int isprime(int x) {
    int prime = 1;
    for (int i=2; i<=floor(sqrt(1.0*x)); i++) {
        if (x % i == 0) {
            prime = 0;
            break;
        }
    }
    return prime;
}

int main(int argc, char **argv) {

    const int MAXN=128;
    int start=200;
    if (argc > 1)
        start = atoi(argv[1]);

    int candidates[MAXN];
    for (int i=0; i<MAXN; i++) {
        candidates[i] = start+i;
    }

    int found=0;
    int value=-1;
    int location=-1;
#pragma omp parallel shared(found, candidates, value, location) default(none)
    {
        int tid=omp_get_thread_num();
        int nthreads=omp_get_num_threads();
        int item=tid;

        while (!found && item < MAXN) {
            int prime=isprime(candidates[item]);
            if (prime) {
                int alreadyfound=0;
#pragma omp atomic capture
                { alreadyfound = found; found++; }
                if (!alreadyfound) {
                    location = item;
                    value = candidates[item];
                }
            }
            item += nthreads;
        }
    }

    if (!found)
        printf("No primes found\n");
    else
        printf("Found prime: %d (%d) in location %d (%d)\n", value, isprime(value), location, candidates[location]);

    return 0;
}

Running gives
$ gcc -o stopwhenfound stopwhenfound.c  -std=c99 -lm -fopenmp
$ ./stopwhenfound 370262
Found prime: 370373 (1) in location 111 (370373)

A: I disagree with Jonathan, I think it is very easy to do in OpenMP. You just need to flush the done variable (so its value is consistent across all the caches):
//Something before
found = 0;
**#pragma omp flush(done)**
while (!found){
  //Pull an element from an array and do some work with it
  if(something){
     found = 1;
     **#pragma omp flush(done)**
     }
  //Do other work and put an element in the same array
}
//Something later


text:
Q: Regex to extract four digits using Java Pattern I'm trying to extract four digits before the file extension using Java Pattern Matchers. It's throwing no group found exception. Can someone help me on this ?
String fileName = "20210101-000000_first_second_1234.csv";
Pattern pattern = Pattern.compile("\\\\d{4}");
System.out.println(pattern.matcher(fileName).group(4));

I would like to get 1234 from the fileName. I compiled the file pattern using regex \\\\d{4}. Which returns four groups. So, fourth group should suppose to return 1234 which is not returning, instead throwing group not found exception.

A: The "\\\\d{4}" string literal defines a \\d{4} regex that matches a \dddd string (a backslash and then four d chars). You try to access Group 4, but there is no capturing group defined in your regex. Besides, you can't access match groups before actually running the matcher with Matcher#find or Matcher#matches.
You can use
String fileName = "20210101-000000_first_second_1234.csv";
Pattern pattern = Pattern.compile("\\d{4}(?=\\.[^.]+$)");
Matcher m = pattern.matcher(fileName);
if (m.find()) {
    System.out.println(m.group());
}

See the Java demo and the regex demo. Details:

*

*\d{4} - four digits

*(?=\.[^.]+$) - a positive lookahead that requires a . char and then  one or more chars other than . till end of string.

Note also the Matcher m = pattern.matcher(fileName) added and if (m.find()) checks if there is a match. Only if there is a match, the value can be retrieved from the 0th group, m.group().

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it necessary to have a co_return statement on each execution path of a coroutine that returns void I wonder whether the below code is valid C++ code or if not using co_return results in undefined behavior.
IAsyncAction MyClass::MyCoroutine()
{
  co_await someOtherClassInstance.SomeCoroutine();
}

I.e. is it necessary to adjust the code as follows?
IAsyncAction MyClass::MyCoroutine()
{
  co_await someOtherClassInstance.SomeCoroutine();
  co_return;
}

If the behavior is not undefined, what is the best practice (always add co_return or not) and what is the justification for doing so?

A: Omitting the co_return; statement is well defined here. According to [stmt.return.coroutine] this is allowed as long as p.return_void() is a valid expression (where p is the promise type).
C++/WinRT implements return_void() for IAsyncAction and IAsyncActionWithProgress (or rather the internal await adapter structs for those).
Since the co_return; statement is purely optional here, it is down to personal preference on whether to use it or not. Personally, I prefer reading code where the co_return; statement is present, for a few reasons:

*

*It allows me to easily comment out part of the coroutine (e.g. for testing) without risking to turn it into a regular function.

*I don't have to know the intricacies of the complex C++/WinRT library to figure out whether the code is correct.

*The code stays correct if I ever decide to change its return type.

A: According to cppreference, the first block would only incur in undefined behaviour if the Promise type has no Promise::return_void() member function:

When a coroutine reaches the co_return statement, it performs the
following:

*

*calls promise.return_void() for

*

*co_return;

*co_return expr where expr has type void

*falling off the end of a void-returning coroutine. The behavior is undefined if the Promise type has no Promise::return_void() member
function in this case.

The Standard draft seems to say the same in other words:

If p.return_void() is a valid expression, flowing off the end of a coroutine's function-body is equivalent to a co_return with no
operand; otherwise flowing off the end of a coroutine's function-body
results in undefined behavior.

[Emphasis mine in both quotes]


text:
Q: Running front- and backend at the same time in electron I am trying to run my express backend simultaneously with my reactjs frontend.
Front- and backend need to be packaged into one single electron app. As I am an beginner in both react and electron, the answer may be obvious.
So the question:
What possible ways are there to achieve described behavior?

A: I found a way. There must be a more elegant one but spawning a child process for the backend in the main process of electron did work great.


text:
Q: Creating link to Outlook messages Outlook 2007
While composing a new message in outlook can a link be created to other messages?
Whww I am composing a new mail I would like to create a link to asent item, clicking this link should then open the message.
Can this be done?

A: Microsoft has a support KB on hyperlinks to access Outlook folders and items:
http://support2.microsoft.com/kb/158135
However, the Outlook: scheme is not registered by default with newer versions of outlook.
http://www.slipstick.com/outlook/using-outlook-links/
I verified that the registry editing technique to associate "outlook:" with opening Outlook items ( http://www.slipstick.com/problems/outlook-missing-outlook-protocol/ ) works for Outlook 2013 on Windows 8.1, so I imagine it would work for earlier versions too.

A: I needed to do the same thing in Outlook 2013. I was able to do so without any registry editing. (I believe such editing is only necessary if you want the links to work outside of Outlook)
I wanted to create a link to an email that I had stored in the following Outlook folder: My Projects\Set 1\. The subject line of the email was Testing links. Here's the steps to do so:

*

*Right-click on the folder in which the target email is stored -> Choose Properties...

*Copy the full Location path (in my case this was \\MyEmail@my.domain\My Projects. (Note that this doesn't include the parent folder itself; Use the description box (or some other convenient location) to paste that path, then append the folder. So in my case the full path looked like \\MyEmail@my.domain\My Projects\Set 1.

*Open up the email that you want to paste the link into.

*Create a normal hyperlink

*In the Address field type Outlook: followed by the path you created in Step 2 above, followed by a backslash and tilde, followed by the subject line of the target email. So for me, that whole address looks like this: Outlook:\\MyEmail@my.domain\My Projects\~Testing links

*Done.


text:
Q: Create a model filed which corresponds to a queryset I am using Python Django. I want to have a dynamic homepage. To be exact, I want to show different lists of books. For example one list might be best sellers and the other might be old books. These lists could be added in the future and I need them to be dynamic. Each list has a title and a queryset corresponding to books within that list. What is the best practice to handle this? What should be the properties of my List model?
Update
The thing is that I do not want to change my front-end design each time that I might have a new list. These lists should be dynamic. For example, I might want to add a new list let's say top of 2018 and I know what the queryset is. I want to have a model such that every instance of that model corresponds to one of these lists and then the only thing I need to do is to create a new instance which has the queryset and title of the list. Then I want my website to return all of these lists when some one requests to get the home page.

A: You should put custom querysets in your model's manager.

A: I wrote a toy example, hope this would help

*

*models.py

*views.py

*html

from django.db import models

class Books(models.Model):
    name = models.CharField(max_length=20)
    best_sellers = models.BooleanField()
from django.shortcuts import render_to_response
from book.models import Books

def book_page(request):
    books = Books.objects.all()
    return render_to_response('book_page.html',locals())
    <!doctype html>

            <title> Book lists </title>
            <meta charset='utf-8'>

            {% for b in books %}
                {% if b.best_sellers %}

{{ b.name }}

                {% else %}

{{ b.name }}

                {% endif %}
            {% endfor %}

A: Sorry not going to give you any code as I am not going to do the work for you. I would suggest you think about how you would want to design your database.
For example, do you want just one model that has all the books and than has a couple fields that indicate if it is a "best seller" or considered an "old book".
So for this case, to find "old books" you might want a timestamp field and then run a query that considers books passed a certain date to be old. That could be one list.
For best sellers, you could have a boolean field where you yourself indicate if that book is a best seller. Then you run a query filtering by that boolean field. That could be another list.
So just think of what are the exact lists you want, and how could you efficiently query for this for this.


text:
Q: Apache nolonger able to start (could not bind to address error) I run a local apahe2 and PHP set up on my Ubuntu desktop to test stuff. Mainly so I can avoid uploading utter garbage when I am creating new code.
However after a particularly problematic upgrade it seems Apache is no longer running. When I try to start or restart it I get this:

 * Restarting web server apache2
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
(13)Permission denied: AH00072: make_sock: could not bind to address [::]:80
(13)Permission denied: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs
Action 'start' failed.
The Apache error log may have more information.
                                                                         [fail]
 * The apache2 instance did not start within 20 seconds. Please read the log files to discover problems

I couldn't rember where the error logs might be found (it has beena  long while) but I googled it: Where are the Apache and PHP log files?
However /var/log/apache2/error.log is empty
How can I figure out what is wrong and fix it?
Notes: I am aware of the whole cannot determine FQDN thing and as I am running it only for me I've never been that bothered so long as it actually worked and I could test what I had written.


text:
Q: What is the difference between the Ubuntu ~ directory and / directory? I'm new to Ubuntu and trying to understand the differences between these two directories. I need to know where node packages, git projects, and dotfiles can be installed to avoid future problems.  Does anybody have a quick layman's answer?
I navigate to each directory in the following ways:
cd ~

or
cd /

Under which of these directories should I install my dotfiles?
Under which of these directories should I install my git projects?
I'm using Git Bash but I can't locate the directory on my machine for git checkouts.

A: See official documentation for the Ubuntu directory tree.  It provides a basic explanation of the hierarchy and purpose of each directory.
cd / is taking you to your "top" or root level directory.
cd ~ is taking you to your current user home directory within /home/ (ex:  /home/username).

Typically, you'll want to place your dotfiles in your user home directory (~/).  If you look at some of the projects in the link you provided, they suggest this as well.
As for your git projects, those can go wherever you see fit.  I prefer to place them within ~/ but it is really a matter of preference.


text:
Q: Open office writter unsaved warning are gone in newer version I'm on ubuntu 20.04, switching from 16.04 and I noticed that libre office writer don't warn me anymore when a document is unsaved. Before there where an icon or *** showing beside the name of the project when unsaved.
It was a little warning that I appreciated a lot in my work dealing with hundred of sheets. Is there a way to configure it again or could I install an old version? I'm planning to use mint one day, can it changes something for my problem?

A: Ah it's funny, I noticed that there is actually a warning , the save icon is an arrow, blue for save, red for unsaved. It is a very small detail, I liked it better with the * beside the title.


text:
Q: Using DISM in code I've been searching to try and find out if its possible to access DISM or any of its command-lets in any form of programming language. I know DISM can be accessed through both powershell and the standard command prompt, but i require that these commands be executed from a program that i am developing.
The program i am developing would require me to be able to remove/uninstall windows 8 apps. From my searching online, DISM seems to be the most 'low-level' way of doing this.
Removing Windows 8 Apps in powershell: http://gallery.technet.microsoft.com/scriptcenter/Remove-Windows-Store-Apps-a00ef4a4
Is it possible to access DISM in code or is it just a pipe dream?

A: Yes, the API is around and in use (ask Nuhi), it's compatible with C,C++, here is a link to get you started.
http://msdn.microsoft.com/en-us/library/windows/desktop/hh824790.aspx
But ps1 is simple enough, why not ps.invoke, much easier and will take you less lines of code.
dism /Image:c:\offline /Remove-ProvisionedAppxPackage /PackageName:Microsoft.Bing_1.2.0.137_x64__8wekyb3d8bbwe
dism /Image:c:\offline /Remove-ProvisionedAppxPackage /PackageName:Microsoft.BingFinance_1.2.0.135_x64__8wekyb3d8bbwe
dism /Image:c:\offline /Remove-ProvisionedAppxPackage /PackageName:Microsoft.BingMaps_1.2.0.136_x64__8wekyb3d8bbwe


text:
Q: Differentiating the minimizers of parametrized convex functions Let $f:\mathbb R^2\to\mathbb R$ be strongly convex in the first argument, and smooth in the second. Consider
$$
\DeclareMathOperator*{\argmin}{argmin}
x_*(y) = \argmin_x f(x, y)\,.
$$
Can we somehow compute $\frac{dx_*}{dy}$ at a point $y$ without explicity computing the function $x_*$?
Whenever $f$ is also smooth in $x$, we have
$$
0=\frac{d}{dy}\frac{\partial f(x_*,y)}{\partial x} = \frac{\partial^2f}{\partial x^2}\frac{dx_*}{dy} + \frac{\partial^2 f}{\partial x\partial y}
$$
and thus
$$
\frac{dx_*}{dy} = -\left( \frac{\partial^2f}{\partial x^2} \right)^{-1}
\frac{\partial^2 f}{\partial x\partial y}   \,.
$$
It would be nice to have something like this when $f$ doesn't have this additional regularity.

Just to provide an illustration:
What would be a good approach for the following example?
$$ f(x,y) = |x-y|^2 + |x|\,. $$
The explicit solutions are
$$
x_*(y) = \begin{cases}
0 & \text{if }y\in(-\frac12,\frac12) \\
y - \frac12 & \text{if }y\ge\frac12 \\
y + \frac12 & \text{if }y\le-\frac12
\end{cases}\,,
\qquad
\frac{d x_*}{dy} = \begin{cases}
0 & \text{if }y\in(-\frac12,\frac12) \\
+1 & \text{if }y>\frac12 \\
-1 & \text{if }y<-\frac12
\end{cases}\,.
$$


text:
Q: How can I get rangeslider.js to work on mobile devices? I have the following problem, you will see I have a web page where I implement the rangeslider plugin on PC it works correctly but on mobile I can't explain myself: when on mobile I select the slider I cannot make it go up or down or change the amount it has, it is only modified while The scroll is used but as you know with the scroll the user moves on mobile, therefore it cannot work so check what I mean on the page
this is the link of the page: http://ucreativa.work/linux/nsite2/product.php
As you can see, it works well on PC, but if they try to use it on mobile, the slider does not work.
What do you think that might be? I append the js code that I use I don't append the css because it is a lot of code that is not relevant
my question is can this plugin work on mobile?

var cpu_cur_val = '2';
var ram_cur_val = '4';
var disk_cur_val = '8';
var backup_cur_val = '30';
var ips_cur_val = '0';

function new_range (wrapper) {
    // Variables to use later
    var rangeWrapper = document.querySelector('.' + wrapper + '__wrapper');
    var rangeInput = document.querySelector('.' + wrapper + '__input');
    var rangeValues = document.querySelector('.' + wrapper + '__values');
    var rangeValueNumberBottom = document.querySelector('.' + wrapper + '__value__number--bottom');
    var rangeValueTextBottom = document.querySelector('.' + wrapper + '__value__text--bottom');
    var rangeSliderPaths = document.querySelectorAll('.' + wrapper + '__slider__path');
    var mouseX = 0;
    var mouseY = 0;
    var mouseInitialY = 0;
    var mouseDy = 0;
    var mouseDyLimit = 25;
    var mouseDyFactor = 3;
    var max = parseInt(rangeInput.max);
    var rangeMin = parseInt(rangeInput.min);
    var rangeMax = parseInt(rangeInput.max);
    var rangeValue = parseInt(rangeInput.value);
    var rangeHeight = 320;
    var currentY = rangeHeight * rangeValue / max;
    var rangeMinY = rangeHeight * rangeMin / max;
    var rangeMaxY = rangeHeight * rangeMax / max;
    var scaleMax = 0.32;
    var scale, newPath, newY, newSliderY, lastMouseDy, rangeWrapperLeft, pageX, pageY;

    // Update slider value, initially using the `input` value
    updateValue();

    // Function to build the slider `path`, using the given `dy` and `ty` values
    function buildPath(dy, ty) {
        return 'M 0 ' + ty + ' q ' + mouseX + ' ' + dy + ' 120 0 l 0 320 l -120 0 Z';
    }

    // Function to update the slider value
    function updateValue() {

        // Clear animations if are still running
        anime.remove([rangeValues, rangeSliderPaths[0], rangeSliderPaths[1]]);

        // Calc the `input` value using the current `y`
        rangeValue = parseInt(currentY * max / rangeHeight);

        // Calc `scale` value for numbers
        scale = (rangeValue - rangeMin) / (rangeMax - rangeMin) * scaleMax;
        // Update `input` value
        rangeInput.value = rangeValue;
        // rangeSum.innerText = rangeValue;
        rangeValueNumberBottom.innerText = rangeValue;
        // Match the javascript value to real input value;
        rangeInput.setAttribute('value', rangeValue);

        switch (wrapper) {
          default:
            rangeValueNumberBottom.innerText = rangeValue;
            break;
          case 'cpu':
            cpu_cur_val = rangeValue;
            break;
          case 'ram':
            if (rangeValueNumberBottom.innerText == '0') {
              rangeValueTextBottom.innerText = 'זיכרון (MB)';
              rangeValueNumberBottom.innerText = '500';
            } else {
              rangeValueTextBottom.innerText = 'זיכרון (GB)';
            }
            ram_cur_val = rangeValue;
            break;
          case 'disk':
            rangeValueNumberBottom.innerText = rangeValue + '0';
            disk_cur_val = rangeValue;
            break;
          case 'backup':
            if (rangeValueNumberBottom.innerText == '0') {
              rangeValueNumberBottom.innerText = '0';
            } else {
              rangeValueNumberBottom.innerText = rangeValue + '0';
            }
            backup_cur_val = rangeValue;
            break;
          case 'ips':
            ips_cur_val = rangeValue;
            break;
        }

        // Some maths calc
        if (Math.abs(mouseDy) < mouseDyLimit) {
            lastMouseDy = mouseDy;
        } else {
            lastMouseDy = mouseDy < 0 ? -mouseDyLimit : mouseDyLimit;
        }

        // Calc the `newSliderY` value to build the slider `path`
        newSliderY = currentY + lastMouseDy / mouseDyFactor;
        if (newSliderY < rangeMinY || newSliderY > rangeMaxY) {
            newSliderY = newSliderY < rangeMinY ? rangeMinY : rangeMaxY;
        }

        // Build `path` string and update `path` elements
        newPath = buildPath(lastMouseDy, rangeHeight - newSliderY);
        rangeSliderPaths[0].setAttribute('d', newPath);
        rangeSliderPaths[1].setAttribute('d', newPath);
    }

    // Function to simulate the elastic behavior
    function elasticRelease() {
        // Morph the paths to the opposite direction, to simulate a strong elasticity
        anime({
            targets: rangeSliderPaths,
            d: buildPath(-lastMouseDy * 1.3, rangeHeight - (currentY - lastMouseDy / mouseDyFactor)),
            duration: 150,
            easing: 'linear',
            complete: function () {
                // Morph the paths to the normal state, using the `elasticOut` easing function (default)
                anime({
                    targets: rangeSliderPaths,
                    d: buildPath(0, rangeHeight - currentY),
                    duration: 4000,
                    elasticity: 880
                });
            }
        });

    }

    // Handle `mousedown` and `touchstart` events, saving data about mouse position
    function mouseDown(e) {
        mouseY = mouseInitialY = e.targetTouches ? e.targetTouches[0].pageY : e.pageY;
        rangeWrapperLeft = rangeWrapper.getBoundingClientRect().left;
    }

    // Handle `mousemove` and `touchmove` events, calculating values to morph the slider `path` and translate values properly
    function mouseMove(e) {
        if (mouseY) {
            pageX = e.targetTouches ? e.targetTouches[0].pageX : e.pageX;
            pageY = e.targetTouches ? e.targetTouches[0].pageY : e.pageY;
            mouseX = pageX - rangeWrapperLeft;
            mouseDy = (pageY - mouseInitialY) * mouseDyFactor;
            newY = currentY + mouseY - pageY;
            // alert(newY);
            if (newY >= rangeMinY && newY <= rangeMaxY) {
                currentY = newY;
                mouseY = pageY;
            } else {
                currentY = newY < rangeMinY ? rangeMinY : rangeMaxY;
            }
            // After doing maths, update the value
            updateValue();
        }
    }

    // Handle `mouseup`, `mouseleave` and `touchend` events
    function mouseUp() {
        // Trigger elastic animation in case `y` value has changed
        if (mouseDy) {
            elasticRelease();
        }
        // Reset values
        mouseY = mouseDy = 0;
    }

    // Events listeners
    rangeWrapper.addEventListener('mousedown', mouseDown);
    rangeWrapper.addEventListener('touchstart', mouseDown);
    rangeWrapper.addEventListener('mousemove', mouseMove);
    rangeWrapper.addEventListener('touchmove', mouseMove);
    rangeWrapper.addEventListener('mouseup', mouseUp);
    rangeWrapper.addEventListener('mouseleave', mouseUp);
    rangeWrapper.addEventListener('touchend', mouseUp);
}


text:
Q: Select element from jQuery object with matching name attribute If I've got a jQuery object that contains input fields like so:
var $inputs = $("#signup input");

Is there a way I can directly select one out of it where the name attribute equals a given value?
I've tried $inputs.find("name=firstName").select();, but it seems not to be working.

A: You need to use attribute-value selector here:
$("#signup input[name=firstName]");

update:
$inputs.filter("[name=firstname]");

Working Demo

A: You were close.
$inputs.filter("[name=firstName]").select();

Or, using my preferred syntax...
$inputs.filter('[name="firstName"]').select();

Demo
http://api.jquery.com/attribute-equals-selector/

A: Use:
$inputs.filter('[name="firstName"]');

Special Note:
.select() is used to select the text in the input but not to select the way you mean.

A: Try
var $inputs = $("#signup");
$("[name=firstName]", $inputs).select();

jsfiddle http://jsfiddle.net/guest271314/571ckuu0/


text:
Q: Swift - Trying to set up a share button I'm trying to set up a share button from a time I previously coded it. I must be missing something, but I'm not sure what. Can you help? This is on a different view controller than the main one.
import UIKit

class MoreViewController: UIViewController, UITabBarDelegate, UITextFieldDelegate {

    @IBAction func shareKnockingBuddy(_ sender: AnyObject) {

    let messageToSend = "Here is a message. \(doorsKnocked)"

    let vc = UIActivityViewController(activityItems: [messageToSend], applicationActivities: nil)
    self.present(vc, animated: true, completion: nil)

  }

  override func viewDidLoad() {
    super.viewDidLoad()

  }

}

Here's my error: On the App delegate it's "Thread 1: signal SIGABRT". On the message thingy on the bottom, it says "* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController shareKnockingBuddy:]: unrecognized selector sent to instance 0x7fe282c02eb0'
* First throw call stack:"

A: Notice the error is about UIViewController and not your MoreViewController class. This means you did not set th proper class name for the view controller in your storyboard. Change it to MoreViewController.


text:
Q: How to fix page scroll freeze bug when scrolling overflowed div? I have a page with Hero section consisting of 2 columns - left one contains gallery slider, right one contains 2 blocks with text. The right one is longer but by design it should be 100% of the screen height. I have set fixed height for the hero and overflow-y: auto. One thing about the design is, that they require when scrolling while hovering over the left column, to scroll the text in the right one to its bottom to show the callout button first and then continue scrolling down the page.
I tried to align the columns with flex, but wanted to make the left column sticky, so I swithced to floated elements. The only problem is that when I scroll to the bottom of the Hero section, I can't scroll further down the page. I need to move the mouse and then it "unlocks" scrolling down. I tried a couple of things with js for example - when reaching the bottom of the section on scroll - to trigger scrolling down but with no luck. The issue persists. I searched thoroughly the net, but couldn't find working solution. Does anyone have any suggestions?

.hero-header {
    height: 100vh;
    overflow-y: auto;
}
.hero-header:after{
    content: '';
    display: table;
    clear: both;
    width: 100%;
}
.main-slider {
    max-width: 63%;
    width: 63%;
    float: left;
    position: sticky;
    top: 0;
}
.slide{
color: green;
font-weight: 700px;
text-align: center;
}
.main-slider_arrow{
  cursor: pointer;
      position: absolute;
      z-index: 10;
      visibility: hidden;
      top: 37vh;
}
#hero-prev{
  left: 20px;
}
#hero-next{
  right: 20px;
}
.main-wrapper {
    max-width: 37%;
    width: 37%;
    float: right;
}

.slider-gallery .slide {
    padding: 8px;
    height: calc(100vh - 61px);
    position: relative;
    margin-top: 61px;
    @media screen and (max-width: 1024px) {
      margin-top: unset;
    }
}

.highlight-box{
height: 545px;
    background-color: #da0f0d;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 102px;
    color: white;

}
.text-container{
  margin-bottom: 20px;
}
.btn{
  min-width: 200px;
  padding: 10px 15px;
  text-align: center;
  text-transform: uppercase;
  background: black;
  color: white;
}

.section{
  text-align: center;
  background: skyblue;
  padding: 80px 100px;
  min-height: 700px;
}

            Prev

                   #slide1

            Next

Title

            5/5

           Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque, culpa!

             Discover More

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

          CALLOUT BTN

NEXT SECTION

A: I've made a few updates to your code to .hero-header container and right sidebar (.main-wrapper), please, take a look

.hero-header {
    height: 100vh;
    /* overflow-y: auto; */
    overflow: hidden;
}
.hero-header:after{
    content: '';
    display: table;
    clear: both;
    width: 100%;
}
.main-slider {
    max-width: 63%;
    width: 63%;
    float: left;
    position: sticky;
    top: 0;
}
.slide{
color: green;
font-weight: 700px;
text-align: center;
}
.main-slider_arrow{
  cursor: pointer;
      position: absolute;
      z-index: 10;
      visibility: hidden;
      top: 37vh;
}
#hero-prev{
  left: 20px;
}
#hero-next{
  right: 20px;
}
.main-wrapper {
    max-width: 37%;
    width: 37%;
    float: right;
    /* try this */
    height: 100%;
    overflow: auto;
}

.slider-gallery .slide {
    padding: 8px;
    height: calc(100vh - 61px);
    position: relative;
    margin-top: 61px;
    @media screen and (max-width: 1024px) {
      margin-top: unset;
    }
}

.highlight-box{
height: 545px;
    background-color: #da0f0d;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 102px;
    color: white;

}
.text-container{
  margin-bottom: 20px;
}

.section{
  text-align: center;
  background: skyblue;
  padding: 80px 100px;
  min-height: 700px;
}

            Prev

                   #slide1

            Next

Title

            5/5

           Lorem ipsum dolor sit amet consectetur adipisicing elit. Cumque, culpa!

             Discover More

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Earum aliquam magni accusamus ex voluptatum distinctio itaque laudantium eos praesentium tempore corporis saepe corrupti, illum at, voluptate eligendi rerum. Repellat explicabo quod obcaecati perspiciatis dolore beatae vitae maiores ad tempora. Nemo deserunt tempora necessitatibus dolorum! Possimus omnis saepe harum corporis iste?

NEXT SECTION


text:
Q: Find the minimum length snippet from the paragraph that contains all the words belonging to a given query in O(n) time Given a review paragraph and keywords, find minimum length snippet from paragraph which contains all keywords in any order.If there are millions of review, what preprocessing step would you do.
The first part is simple, just the minimum window problem. Now, for preprocessing, I use inverted index. So, for each review I build a table storing the list of occurance of each word. Now, when a query comes, I retrieve the list of indices for each word. Now, is there some way to find out the min window length from this set of list in O(n) time? I tried building min and max heap to store the current index of each list and then keeping a track of the min window length(using the root of both the heaps). Then I perform extractMin operation and remove the same element from the max heap as well. To keep address of the location of each element in the max heap(for removal), I maintain a hash table. Now from the list, to which the extracted element belonged, I insert the next element into both the heaps and change the window length, if needed. This takes O(nlog n) time. Is it possible to do this in O(n) time?

A: Assuming this combination is sorted here is how I would do it:

*

*Create a list of objects that describe the word and its index, Something like Obj(String name,Int index).

*Init a set containing all keywords of the query.

*Init the lower bound of the window as the index of the first element in the list.

*Go through the list updating the upper bound of the window as the current object's index, updating the lower bound of the window as the index of the first occurrence of any of the words in your query (i.e. once min_window is set to the index of an actual word occurrence it is no longer updated) and by removing the corresponding word from the set of keywords.

*When the set is empty, save the resulting lower and upper bound along with the length of the snippet.

*Repeat the steps 2 to 5 but this time the list you're going to use is the list that starts at the element that comes right after the one defined by the previous min_window and by only keeping the min_window and max_window if the length of the snippet is shorter than the previous one (this should be repeated until you can no longer find all occurrences in the given sublist).

A: #include<bits/stdc++.h>
using namespace std;
map<string,int>word;
void functionlower(string& str){
    transform(str.begin(),str.end(),str.begin(),::tolower);
}
string compareWord(string& str){
    string temp;
    temp.resize(str.size());
    transform(str.begin(),str.end(),temp.begin(),::tolower);
return temp;
}
int main(){
int total_word;
cin>>total_word;
for(int i=0;i<total_word;i++){
    string str;
    cin>>str;
    functionlower(str);
    word.insert({str,0});
}

cin.ignore();
string str;
vector<string>para;
getline(cin,str);
int index=0;
for(int i=0;i<=str.size();i++){
    if(i==str.size()||str[i]==' '){para.push_back(str.substr(index,i-index)); index=i+1;}
}
int currlen=0;
int currpos=0;
int lenprint=0;
int olen=-1;
int opos=-1;
for(int i=0;i<para.size();i++){
    string search=compareWord(para[i]);
    if(word.find(search)!=word.end()){
        if(word[search]==0)currlen++;
        word[search]++;
    }
    while(currlen>=word.size()){
        search=compareWord(para[currpos]);
        if((i-currpos)<olen||olen==-1){
            olen=i-currpos;
            opos=currpos;
        }
        if(word.find(search)!=word.end()){
            if(word[search]==1)break;
            word[search]--;
            currpos++;
            lenprint=i;
        }else currpos++;
    }
}
for(int i=0;i<=olen;i++){
cout<<para[opos+i]<<" ";
}
cout<<endl;
return 0;
}

O(nlogk) where k is number of words need to search

A: Assuming a constant wordLength, this solution can be achieved in O(n) time complexity, where n is number of words in para; here is the code for implementation in java:
package Basic.MinSnippetWithAllKeywords;

import java.util.*;

/**
 * Given a review paragraph and keywords,
 * find minimum length snippet from paragraph which contains all keywords in any order.
 */

public class Solution {
    public String minSnippet(String para, Set<String> keywords) {
        LinkedList<Integer> deque = new LinkedList<>();
        String[] words = para.split("\\s");
        for (int i = 0; i < words.length; ++i) {
            if(keywords.contains(words[i]))
                deque.offer(i);
        }

        while(deque.size() > 1) {
            int first = deque.pollFirst();
            int second = deque.peekFirst();
            if (words[first] != words[second]) {
                deque.offerFirst(first);
                break;
            }
        }

        while(deque.size() > 1) {
            int first = deque.pollLast();
            int second = deque.peekLast();
            if(words[first] != words[second]) {
                deque.offerLast(first);
                break;
            }
        }
        if (deque.isEmpty())
            return "";

        return String.join(" ",
                Arrays.copyOfRange(words, deque.peekFirst(), deque.peekLast() + 1));
    }
    /*
    Example:
    my name is shubham mishra
    is name
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String para = sc.nextLine();
        String keyLine = sc.nextLine();
        Set<String> keywords = new HashSet<>();
        keywords.addAll(Arrays.asList(keyLine.split("\\s")));
        System.out.println(new Solution().minSnippet(para, keywords));
    }
}


text:
Q: Change tabbar selected item from another view controller I am new to Swift (using 4 version) and I want to change tab bar item from another view controller (not tab bar controller).
This is my scheme:

From RouterViewController (used for side menu navigation) in didSelectRowAt i'm doing this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let mainViewController = sideMenuController!

    let tabBarController : TabBarController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TabBarController") as! TabBarController

    tabBarController.selectedIndex = indexPath.row
}

It's not throwing any exceptions and debugging shows, that let tabBarController is not null, but it's not changing tab for some reason.
What am I doing wrong?

A: Try this:
self.tabBarController.selectedIndex = 1;
self.tabBarController setSelectedIndex:1];

or
self.tabBarController.selectedViewController = yourViewController;
self.tabBarController setSelectedViewController:yourViewController];

A: You can define this variable in the appDelegate:
var window: UIWindow?
let tabViewController = self.window!.rootViewController as! UITabBarController

Now you can use the tabViewController variable in all your code and invoke the methods on this, like the method to change page.
For all the methods/variables of the UITableViewController see the documentation at this link:
https://developer.apple.com/documentation/uikit/uitabbarcontroller
I think that change the variable "var selectedIndex: Int" will solve your problem.


text:
Q: Cassandra SSTable, Space Usage, Memtable size is 0 although table has some data I created a table with ~20 columns and ~100 rows. I can see everything as 0 in terms of space while querying space usage of the table.
It returns data upon querying.
Other tables in the same keyspace have numbers in 'Space used' or 'Memtable data size' fields.
Cassandra version 3.0
SSTable count: 0
    Space used (live): 0
    Space used (total): 0
    Space used by snapshots (total): 0
    Off heap memory used (total): 0
    SSTable Compression Ratio: -1.0
    Number of partitions (estimate): 0
    Memtable cell count: 0
    Memtable data size: 0
    Memtable off heap memory used: 0
    Memtable switch count: 0
    Local read count: 0
    Local read latency: NaN ms
    Local write count: 0
    Local write latency: NaN ms
    Pending flushes: 0
    Percent repaired: 100.0
    Bloom filter false positives: 0
    Bloom filter false ratio: 0.00000
    Bloom filter space used: 0
    Bloom filter off heap memory used: 0
    Index summary off heap memory used: 0
    Compression metadata off heap memory used: 0
    Compacted partition minimum bytes: 0
    Compacted partition maximum bytes: 0
    Compacted partition mean bytes: 0
    Average live cells per slice (last five minutes): 1.0
    Maximum live cells per slice (last five minutes): 1
    Average tombstones per slice (last five minutes): 1.0
    Maximum tombstones per slice (last five minutes): 1
    Dropped Mutations: 0


text:
Q: How can I select an element from an jQuery object? Say I have the following code:

A

B

//JS

var obj = $('.foo');

Now I want to get the text from t2 element. How do I select this using my obj object?
This does not work: var txt = $(obj + '.t2').text();
This works fine: var txt = obj.find('.t2').text();
I also know I can use this var txt = $('.foo .t2').text();
But I'm thinking that using .find() requires more resources than selecting it directly. Is there a way I can select child element directly using my obj ?

A: Taking this an attempt at a time:
var txt = $(obj + '.t2').text();

This does not work because you are trying to append a string to an object, the result of which will not be a valid selector.
var txt = obj.find('.t2').text();

This will look for the .t2 element within the cached subset of elements in the original selector. This is the best method to use for your scenario and actually uses less resources than example 3:
var txt = $('.foo .t2').text();

which will also work, however it will require jQuery to scan the DOM again, which is something which should be avoided where possible.

A: You could try
 obj.children().eq(1).text()

This way you access the children of your obj variable, take the second (0 based index) and access its text.

A: If your condition is that you have to go through your obj element, then I believe find() is the way to go.  I didn't see anything in jQuery's documentation on find() regarding if it's efficiency vs a direct selector, but I think the fact that you're only searching descendents of your obj with find() means it can't be too inefficient.
obj.find('.t2').text()

A: The most direct way to select children would be to get all children and access them by index:
var ch = obj.children();
var text = ch.eq(1).text();

This naturally means that you have to know the order of the child elements.
You can use a selector in the children method. That will get the children that matches the selector, but the only difference from using find is that it only looks for immediate children, so in your case it works the same:
var text = obj.children('.t2').text();


text:
Q: Adding antialiasing I am trying to using antialiasing but I don't why it isn't working:
Pen pen = new Pen(Color.Black, 3);
Pen r = new Pen(Color.YellowGreen, 3);
Graphics b = panel2.CreateGraphics();
b.DrawEllipse(pen, 6, 0, 90, 90);
b.SmoothingMode = SmoothingMode.AntiAlias;
b.DrawLine(r, new Point(50, 90), new Point(50, 0));

A: First it should be noted that the Graphics object does not contain any graphics; it is a tool that lets you draw onto a related bitmap, including a control's surface. Therefore changing any of its properties, like the SmoothingMode only influences graphics you draw from then on, not anything you have drawn before..
The circle certainly would have antialised pixels if you would draw it after setting the SmoothingMode from its default None to AntiAlias.
The Line is vertical, so it doesn't need antialiasing except at its ends, where there is some. But if you tilt it or move it to a non-integer position anti-aliasing will show!
Let's modify your code a little and look closely at the result:
Pen pen = new Pen(Color.Black, 3);
Pen r = new Pen(Color.YellowGreen, 3);
Graphics b = panel2.CreateGraphics();
b.DrawEllipse(pen, 6, 6, 90, 90);
b.SmoothingMode = SmoothingMode.AntiAlias;
b.DrawLine(r, new Point(50, 90), new Point(50, 0));

b.DrawLine(r, new Point(60, 90), new Point(70, 0));
b.DrawLine(r, new PointF(40.5f, 90), new PointF(40.5f, 0));
b.DrawEllipse(pen, 6, 6, 30, 30);

The smaller circle has many gray pixels and even the original green line has a lighter top end. The two new lines are fully anti-aliased now, one because it is tilted,  the other because it sits 'between' pixels.
Btw: If it is turned on you will also see anti-alising when your Pen.Width is even or when it is a non-integer number. The reason for the latter should be obvious; the former comes from the PenAlignment property. Its default Center tries to center the pen, but not at the pixel boundary but at the center of the coordinate pixels. Therefore only an uneven width will completely fill the pixels and not cause anti-aliasing. For closed shapes you can change this behaviour by changing the Pen.Alignment to Inset:

This property determines how the Pen draws closed curves and
  polygons. The PenAlignment enumeration specifies five values;
  however, only two values—Center and Inset—will change the appearance
  of a drawn line. Center is the default value for this property and
  specifies that the width of the pen is centered on the outline of the
  curve or polygon. A value of Inset for this property specifies that the
  width of the pen is inside the outline of the curve or polygon. The
  other three values, Right, Left, and Outset, will result in a pen that
  is centered.
A Pen that has its alignment set to Inset will yield unreliable
  results, sometimes drawing in the inset position and sometimes in the
  centered position.Also, an inset pen cannot be used to draw compound
  lines and cannot draw dashed lines with Triangle dash caps.

PS: The question was not about how to draw properly, so let me just note that you never ought to do it using control.CreateGraphics as this will always only result in non-persistent graphics. Instead you need to use the Paint event and its e.Graphics object..


text:
Q: Error with super. in JAVA I'm learning JAVA and currently I've got a problem with the use of super.
For some reason it displays an error:

Exception in thread "main" java.lang.Error: Unresolved compilation
  problems:     The field Animal.n is not visible   The field Animal.m is
  not visible*

How do I fix it? I realize that String n and int m are set to private, as I am trying to utilize the "super.". Thank you in advance. The part of the code below i'm having problem with is the "super(n,m)
public class Zoo

{

public static void main(String[] args)
  {
    Animal[] cat= new Animal[5];
    BigAnimal big = new BigAnimal("Roro",20,true,true);

    cat[0] = new Animal ("Mauie",5,true);
    cat[1] = new Animal ("Frankie",7,false);
    cat[2] = new Animal ("Zo-Zo",8,false);
    cat[3]=  new Animal ("Alice",12,true);
    cat[4]= big;

    System.out.println(cat[0].getName());
    System.out.println(cat[0].something(10));

  }

}

class Animal

{

    private String n;
    private int m;

    public Animal(String name,int meals, boolean doesitbite)

    {
        n=name;
        m=meals;
    }

}

class BigAnimal extends Animal

{
     boolean doesitlove;

     public BigAnimal (String name, int meals, boolean doesitbite, boolean doesitlove)
        {

            super(n,m);
            doesitlove=true;
        }

}

A: In the constructor for BigAnimal, change
super(n,m);

to
super(name, meals)

That is, pass the values given to BigAnimal constructor to the superclass constructor.
Also, fix your bug(?) and either give the super class a constructor with just two parameters or pass a 3rd parameter to the constructor you've got.  E.g.,
super(name, meals, doesitbite)


text:
Q: Using ModelBuilder to run clip scenario? I am using ArcMap 10.5.
I have a layer representing suburbs (n=432) over laid with open space data (both gdb files).
My objective is to get to get the suburbs to individually clip with the open space data, so far everything I have tried has failed. Suburbs with open space traversing the boundary have not been clipped.
I have tried a few models in ModelBuilder with little success.
Watched numerous YouTube videos on Iterate but nothing appears to match my project.
I am a novice in this area of ArcGIS.

A: Recognizing a clip only works on one polygon, I had 432 adjoining polygons so a new approach was required other than manually clipping 432 suburb boundaries, a time consuming process. Model builder and the iterate function through the iterate feature selection. Utilizing the field "objectid" within my suburb dataset and the null value >=0. generated the output I_SSC2016_OBJECTID in the selected features. Clip, input feature the open space data and the clip feature: I_SSC2016_OBJECTID. Clicking on the clip OK joined the iterate and clip together. The tick button on the model builder tool bar validated the processes and enabled the Run function to work. The iterate process identified each objectid number and clipped it to the open space data. The processed only saved suburbs that contained open space data to the Catalog as individual gdb files. The merge function rejoined the Output_Clip_Open_Space_1 through to Output_Clip_Open_Space_432 back into one dataset.


text:
Q: How to change default password in GeoServer I started to learn GeoServer to publish online maps.
I installed the software and now I would like to change the default password. At the moment is: geoserver
I tried to do it without result.
Can anyone explain me how to do this?


text:
Q: JavaScript text is not showing I am having trouble with this html loading javascript animation - from https://codepen.io/atunnecliffe/pen/siqjd
The script is not printing the text inside the javascript but the screen is fading out at the end, like in the codepen example. Here is the JS right now:
var textarea = $(".term");
var speed = 50; //Writing speed in milliseconds
var text = "sh andrew_website.sh";

var i = 0;

runner();

function runner() {
  textarea.append(text.charAt(i));
  i++;
  setTimeout(function () {
    if (i < text.length) runner();
    else {
      textarea.append("
");
      i = 0;
      setTimeout(function () {
        feedbacker();
      }, 1000);
    }
  }, Math.floor(Math.random() * 220) + 50);
}

var count = 0;
var time = 1;
function feedbacker() {
  textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
  if (time % 2 == 0) {
    i++;
    textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
  }
  if (time == 3) {
    i++;
    textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
    i++;
    textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
    i++;
    textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
  }
  window.scrollTo(0, document.body.scrollHeight);
  i++;
  time = Math.floor(Math.random() * 4) + 1;
  count += time;
  setTimeout(function () {
    if (i < output.length - 2) feedbacker();
    else {
      textarea.append("
Initialising...
");
      setTimeout(function () {
        $(".load").fadeOut(1000);
      }, 500);
    }
  }, time);
}

var output = [

One error that has occurred is the VAR speed is defined but not used anywhere in the JS code however I am at a loss of as to where it could be used. Any help would be appreciated, Thanks, Oliver.

A: Make sure to embed jQuery, works fine for me.

var textarea = $('.term');
var speed = 50; //Writing speed in milliseconds
var text = 'sh andrew_website.sh';

var i = 0;

runner();

function runner() {
  textarea.append(text.charAt(i));
  i++;
  setTimeout(
    function() {
      if (i < text.length)
        runner();
      else {
        textarea.append("
")
        i = 0;
        setTimeout(function() {feedbacker();}, 1000);
      }
    }, Math.floor(Math.random() * 220) + 50);
}

var count = 0;
var time = 1;
function feedbacker() {
  textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
  if (time % 2 == 0) {
    i++;
    textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
  }
  if (time == 3) {
    i++;
    textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
    i++;
    textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
    i++;
    textarea.append("[    " + count / 1000 + "] " + output[i] + "
");
  }
  window.scrollTo(0, document.body.scrollHeight);
  i++;
  time = Math.floor(Math.random() * 4) + 1;
  count += time;
  setTimeout(
    function() {
      if (i < output.length - 2)
        feedbacker();
      else {
        textarea.append("
Initialising...
");
        setTimeout(function() {$(".load").fadeOut(1000);}, 500);
      }
    },time);
}

var output = ["TESTING",
"WORKING",

"fsdfsdfsdfsdf",
"Initialising...", ""];
html,
body {
  margin: 0 auto;
  height: 100%;
}

pre {
  padding: 0;
  margin: 0;
}

.load {
  margin: 0 auto;
  min-height: 100%;
  width: 100%;
  background: black;
}

.term {
  font-family: monospace;
  color: #fff;
  opacity: 0.8;
  font-size: 2em;
  overflow-y: auto;
  overflow-x: hidden;
  padding-top: 10px;
  padding-left: 20px;
}

.term:after {
  content: "_";
  opacity: 1;
  animation: cursor 1s infinite;
}

@keyframes cursor {
  0% {
    opacity: 0;
  }
  40% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

andrew@dev:~$


text:
Q: Angular Universal renders page in wrong way without events I migrated this page: https://www.beta.rohub.org to Angular 7  and started to make this page served on Server side rendering by using Angular universal.
The page is rendered, template works, some requests are working, and the page looks normal.
There are some things which are not working.
For Example:

*

*click events - are not working totally, there are only buttons not
working

*view child

*Directives

*NgModel - values from ngmodel are not working after change

*local storage and cache

*routing - some components can't initialize after going to example on component for showing research Object.

*Host Listeners

The Dist folder is generating correctly.
Here is my code. I don't know what is wrong with this all configs.
angular.json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ng-universal-demo": {
      "projectType": "application",
      "root": "",
      "sourceRoot": "src",
      "schematics": {
        "@schematics/angular:component": {
          "style": "css"
        }
      },
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "outputPath": "dist/browser",
            "index": "src/index.html",
            "main": "src/main.browser.ts",
            "tsConfig": "tsconfig.browser.json",
            "polyfills": "src/polyfills.ts",
            "aot": true,
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              },
              {
                "glob": "favicon.ico",
                "input": "src",
                "output": "/"
              }
            ],
            "styles": [
              "src/styles.css",
              "src/bootstrap.min.css",
              "./node_modules/ng2-tree/styles.css"
            ],
            "scripts": ["./node_modules/quill/dist/quill.min.js"],
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js",
              "replaceDuplicatePlugins": true,
              "mergeStrategies": {
                "externals": "prepend"
              }
            },
            "serviceWorker": true
          },
          "configurations": {
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ng-universal-demo:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ng-universal-demo:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ng-universal-demo:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [],
            "styles": [
              "src/styles.css"
            ],
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              },
              {
                "glob": "favicon.ico",
                "input": "src",
                "output": "/"
              }
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist/server",
            "main": "src/main.server.ts",
            "tsConfig": "tsconfig.server.json"
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          }
        }
      }
    },
    "ng-universal-demo-e2e": {
      "root": "e2e",
      "projectType": "application",
      "cli": {},
      "schematics": {},
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "./protractor.conf.js",
            "devServerTarget": "ng-universal-demo:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "cli": {},
  "schematics": {
    "@schematics/angular:class": {
      "spec": false
    },
    "@schematics/angular:component": {
      "spec": false,
      "inlineStyle": true,
      "inlineTemplate": true,
      "prefix": "app",
      "styleext": "css"
    },
    "@schematics/angular:directive": {
      "spec": false,
      "prefix": "app"
    },
    "@schematics/angular:guard": {
      "spec": false
    },
    "@schematics/angular:module": {
      "spec": false
    },
    "@schematics/angular:pipe": {
      "spec": false
    },
    "@schematics/angular:service": {
      "spec": false
    }
  }

package.json:

  "name": "ng-universal-demo",
  "version": "0.0.0",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/angular/universal-starter.git"
  },
  "contributors": [],
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "lint": "ng lint ng-universal-demo",
    "build:client-and-server-bundles": "ng build --prod  --output-hashing=none && ng run ng-universal-demo:server:production",
    "build:prerender": "npm run build:client-and-server-bundles && npm run compile:server && npm run generate:prerender",
    "build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
    "compile:server": "tsc -p server.tsconfig.json",
    "webpack:server": "webpack --config webpack.server.config.js --progress --colors",
    "generate:prerender": "cd dist && node prerender",
    "serve:prerender": "cd dist/browser && http-server",
    "serve:
ssr": "node dist/server"
  },

server.ts
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';
enableProdMode();

const app = express();
const PORT = process.env.PORT || 3000;
const DIST_FOLDER = join(process.cwd(), 'dist');

const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require( './dist/server/main');
import { ngExpressEngine } from '@nguniversal/express-engine';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "skipLibCheck": true
  }
}

tsconfig.app.json
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "es2015",
    "types": [
      "node"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  "angularCompilerOptions": {
    "entryModule": "app/app.server.module#AppServerModule"
  }
}

webpack.server.config.js
var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: { server: './server.ts' },
  resolve: { extensions: ['.js', '.ts'] },
  target: 'node',
  mode: 'none',
  // this makes sure we include node_modules and other 3rd party libraries
  externals: [/node_modules/],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  module: {
    rules: [{ test: /\.ts$/, loader: 'ts-loader' }]
  },
  plugins: [
    // Temporary Fix for issue: https://github.com/angular/angular/issues/11580
    // for 'WARNING Critical dependency: the request of a dependency is an expression'
    new webpack.ContextReplacementPlugin(
      /(.+)?angular(\\|\/)core(.+)?/,
      path.join(__dirname, 'src'), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      /(.+)?express(\\|\/)(.+)?/,
      path.join(__dirname, 'src'),
      {}
    )
  ]
};

main.server.ts
export {AppServerModule} from './app/app.server.module';
import { enableProdMode } from '@angular/core';

enableProdMode();

A: I solved problem.
A firts thing was docuemnt.cookies and window. on my ts code. So I modificated cookies by ngx-cookies-service like this:
commons.service.ts
import {CookieService} from 'ngx-cookie-service';

...

constructor(private configurationService: ConfigurationService,
              private cookies: CookieService) {

  }

....

if (name === 'accountType') {
      const cookiesArray = Object.keys(this.cookies.getAll());
      console.log(cookiesArray);
      if (cookiesArray.length >= 1) {
        console.log('COOKIES', cookiesArray, 'END OF COOKIES');
        const objectOfCookies = this.cookies.getAll(),
          arrayOfCookies = Object.keys(objectOfCookies),
          typeIndex = arrayOfCookies.indexOf(name);

        if (typeIndex !== -1) {
          const arrayOfAccounts = ['ORCID', 'GOOGLE', 'EVEREST'];
          for (const currentElement of arrayOfAccounts) {
            if (arrayOfCookies.indexOf(currentElement) !== -1) {
              this.properCookieValue = currentElement;
              break;
            }
          }
        } else {
          this.properCookieValue = null;
        }
      }
    } else {

Second thing: Everything with my files was ok, the only thing on server.ts needed a change.
So server.ts looks like that:
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import * as cookieParser from 'cookie-parser';
import { join } from 'path';
import { readFileSync } from 'fs';
enableProdMode();
const domino = require('domino');
const app = express();
const PORT = process.env.PORT || 3000;
const DIST_FOLDER = join(process.cwd(), 'dist');

const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require( './dist/server/main');
import { ngExpressEngine } from '@nguniversal/express-engine';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();
const win = domino.createWindow(template);
global['window'] = win;
global['document'] = win.document;
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

app.use(cookieParser('Your private token'));
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});


text:
Q: How to keep a clean development DB while using Rails Mailer Preview If you are like me, your development Rails BD is for fudging some data. Even if not everything is perfect like my production database, I try to not insert so much junk data so I can at least control my development expectations.
By using FactoryBot or plain RoR you can create in memory object and run the very nice ActionMailer::Preview tool in the development version of RoR. This will save you tons of time if you have to adjust HTML and CSS.
But what about a view that require a BD access ? This happen to me as I need a table to present some user information from the database.
If you use create or FactoryBot.create you'll end up with a lot of records in your BD that you don't really need.
The question then is how to manage a cleanup of the data after the previewer run?

A: Based on suggestion of my friend, he comes up with the idea of a around filter that look like this.
class UserMailerPreview < ActionMailer::Preview

  def welcome_email
    around_email do
      UserMailer.with(user: user).welcome
    end
  end

  private

  def user
    @user ||= FactoryBot.create(:user)
  end

  def around_email
    message = nil
    begin
      ActiveRecord::Base.transaction do
        message = yield
        message.to_s # This force the evaluation of the message body instead of the lasy render
        raise ActiveRecord::Rollback
      end
    rescue ActiveRecord::Rollback
    end
    message
  end
end

This cute trick will create all the data you need, render the email body and clean the database. So you can create as much junk you need for your email without having a burden on your personnal work.


text:
Q: What is the meaning of external force in the Newtonian force equation? I came across the following in Goldstein's Classical Mechanics book, section 1.3.
In a system of particles, the equation of motion for the $i$'th particle is to be written
$$ \sum_j F_{ji}+F_i^{(e)}= \frac{dp_i}{dt}$$ where $F_i^{(e)}$ stands for an external force and $F_{ji}$ is the internal force on the $i$'th particle due to the $j$'th particle.
My question is: what is the meaning of this equation? In the external force $F_i^{(e)}$ why don't we use $j$'th particle symbol? That is, why don't we use $F_{ji}^{(e)}$? If it is meaningless, then how? I'm new to physics, so I would appreciate an explanation.

A: $F_i^{(e)}$ is the external force on the $i^{th}$ particle - that is, the force on the $i^{th}$ particle which cannot be attributed to any other particle in the system - whereas  $F_{ji}$ is the force on the $i^{th}$ particle due to the $j^{th}$ particle.  The expression for the total force is then
$$\frac{d\mathbf p_i}{dt} = \underbrace{\mathbf F^{(e)}_i}_{\text{external}}+ \underbrace{\sum_j \mathbf F_{ji}}_{\text{internal}}$$

As an example, consider a system of 3 particles under the influence of gravity.  The net force on particle $1$ is
$$\frac{d\mathbf p_1}{dt} = \underbrace{(-mg \hat y)}_{\text{external}} + \underbrace{(\mathbf F_{21} + \mathbf F_{31})}_{\text{internal}}$$
where $\mathbf F_{21}$ and $\mathbf F_{31}$ are the forces on particle $1$ due to particles $2$ and $3$, respectively.

A: What Goldstein is referring to here is how one particle in an object responds to a force. $F_i^{(e)}$ would be something like gravity acting on the particle directly. In all likelihood $F^{(e)}$ also acts on particle j, but we don't need to know that in order to calculate $\frac{dp_i}{dt}$. Whatever it is that the external force does to particle j is accounted for in $F_{ji}$.
For example, a particle in a ball on a table feels pressure from the particle above it because gravity is acting as $F^{(e)}$ on it. That gives $F_{ji}$ its value.

A: We are calculating change in moment of "i"th particle so it is sum of all forces applied by other particles and external forces acting on "i"th particle.


text:
Q: Apache with mixed HTTP only and HTTPS virtualhosts I have Apache 2.4 on Debian 8 and few HTTP only name-based virtualhosts and (for now) just 1 HTTPS virtualhost signed by Let's Encrypt certificate. At this moment secured virtualhost works well, but if I visit other non-secured virtualhosts with https:// I get content of the secured virtualhost. Is there some way to (in this case) make some redirection to HTTP or avoid loading content of the secured virtualhost site?

A: Of course redirecting from https to http is possible with:
<VirtualHost *:443>
    ServerName www.example.com
    ServerAlias example.com

    SSLEngine on
    # All other SSL settings, just like in your working TLS VirtualHost.

    Redirect / http://www.example.com/
</VirtualHost>

You just have to understand that:

*

*This will first give a warning "Your connection is not private", because the hostname in HTTP Host: header doesn't match the your certificate, i.e. NET::ERR_CERT_COMMON_NAME_INVALID. Of course this is something you already get.

*Normal users don't write http:// or https:// in the address bar, just the www.example.com, which gets by default completed with http://. (Actually, some users don't even know about the address bar, but uses Google search instead, then picking the first result.)

I'd rather create a catch-all virtualhost with some default page explaining that there is no TLS site configured for this domain. Make sure this comes before the working virtualhost by using a filename that gets first on apache2/sites-enabled, like 001-tls, and use <VirtualHost _default_:443>.

A: You are contradicting yourself. You can't visit non-secured virtualhosts using "https", https by default means port 443, which is the SSL virtualhost in all but rare cases, you will always land in your SSL virtualhost/s then.


text:
Q: Transfer list of data from gridview to another page I have gridview look like this
Any time user click on Bookmark button, I wanna send the ProgramID of that row to the List and transfer it to another page by using Session.But my gridview transfer the all programID, even though that ID existed in the list. What am I doing wrong?
This is the code for Bookmark button:
protected void btnSelect_Click(object sender, EventArgs e)
{

   Button b = (Button)sender;
    GridViewRow row = (GridViewRow)b.NamingContainer;
    var ProgramID = row.FindControl("lblProgramID") as Label;
    string stringProgramID = ProgramID.Text;
    List<string> bookmarkPrograms = (List<string>)Session["BookmarkProgram"];
    if (bookmarkPrograms == null)
        bookmarkPrograms = new List<string>();
    bookmarkPrograms.Add(stringProgramID);
    Session["BookmarkProgram"] = bookmarkPrograms;

}

And here is the code for the gridview in another page:
 protected void Page_Load(object sender, EventArgs e)
{
    List<string> bookMarkPrograms = (List<string>)Session["BookmarkProgram"];

    GridView1.DataSource = bookMarkPrograms;
    GridView1.DataBind();
}

A: Just want to post the whole solution for someone need it in the future:
 protected void btnBookmark_Click(object sender, EventArgs e)
{

    Button b = (Button)sender;
    GridViewRow row = (GridViewRow)b.NamingContainer;
    var ProgramID = row.FindControl("lblProgramID") as Label;
    string stringProgramID = ProgramID.Text;
    List<string> bookmarkPrograms = (List<string>)Session["BookmarkProgram"];
    if (bookmarkPrograms == null)
        bookmarkPrograms = new List<string>();

    if (bookmarkPrograms.Any(c => c.Equals(stringProgramID)))
    {
        FormMessage.Text = "You bookmarked this program already";
    }
    else
    {
        bookmarkPrograms.Add(stringProgramID);
    }
    Session["BookmarkProgram"] = bookmarkPrograms;

}

A: Not really sure about the flow of events. But if I get you correctly, you want the list to be constantly adding. You are doing
 Session["BookmarkProgram"] = bookmarkPrograms;

Which means that this variable is that specific value. But then if you do it again then this happens:
   List<string> bookmarkPrograms = new List<string>();

So you are erasing the old one.  Make a method of getting the list so far, if is null or empty then create a new one.  Otherwise don't or you'll empty what you have so far.
Update:  You can try this:
List<string> bookmarkPrograms = (List<string>)Session["BookmarkProgram"] == null ? new List<string>():(List<string>)Session["BookmarkProgram"];

For checking if the value exists already then:
if (bookmarkPrograms.Any(c=>c.Equals(ProgramID)){//don't add}

The inside expression returns a boolean that is true when a value inside the list equals what you are comparing. This example asumes ProgramID is a string. As they are string you might want to add trim() and tolower() but doesn't seems like in this case a blank space might accidentally be added... or that casing might affect. Since this returns true for when it exists, add a ! in front of it so it adds to the list when it doesn't exists.