text:
Q: 3x3 Tic-Tac-Toe in C using Minimax Note #1 - There is a similar question but that is in Python, and I can't figure out this in C.
Note #2 - This is a human vs. AI game and I will call the AI as 'cpu'. The cpu symbol is 'O' and human symbol is 'X' always.
Note #3 - I want to design the game so that the cpu never loses (either win or draw).
I want the user to go first and choose any of the 9 squares. So basically I want the cpu to brute force calculate the result of every way the game can go, and based on that assign 'scores' to its possible moves (8 remaining choices). This way it backtracks and knows which way to go so as to not lose.
Also I want to do that using the minimax algorithm, and in C.
My problem - What I think is that I'm missing a function that actually makes use of the returned 'scores'. I do not want the code, but I would appreciate it if I could get an idea of how to implement that function. Also the nextMove() function confuses me, I want it to check if there is no unfilled box, then fill it with 'O' and then it's the player's turn. But since it will be called again in the recursion, it might not work correctly. Any suggestions?
Edit - The bounty goes to the answer that guides me on how to implement this game using minimax algorithm as described here: https://en.wikipedia.org/wiki/Minimax#Pseudocode
#include <stdio.h>
#define FALSE 0
#define TRUE 1
#define NEGINF -10000
#define POSINF +10000

struct node { // each node is like a snapshot of the game at that point in time
    char board[9]; // the 3x3 square is implemented as an array of 9 chars
    int value; // the value of that snapshot (+1 if cpu wins, -1 if cpu loses, 0 for draw)
    int position; // 0 to 8 inclusive with 0 being [0][0] and 8 being [2][2] (row major fashion) and indicates position where the next 'X' or 'O' would be assigned
};

int max(int value, int returnedValue) {
    return value > returnedValue ?  value :  returnedValue;
}

int min(int value, int returnedValue) {
    return value < returnedValue ?  value :  returnedValue;
}

int someoneHasWon(struct node someNode) {
    if(someNode.board[0] == someNode.board[3] && someNode.board[3] == someNode.board[6] && someNode.board[6] == 'X')
        return TRUE;

    if(someNode.board[0] == someNode.board[3] && someNode.board[3] == someNode.board[6] && someNode.board[6] == 'O')
        return TRUE;
        //someNode.value = -1;
    if(someNode.board[1] == someNode.board[4] && someNode.board[4] == someNode.board[7] && someNode.board[7] == 'X')
        return TRUE;
        //someNode.value = 1;//return 1;
    if(someNode.board[1] == someNode.board[4] && someNode.board[4] == someNode.board[7] && someNode.board[7] == 'O')
        return TRUE;
        //someNode.value = -1;//return -1;
    if(someNode.board[2] == someNode.board[5] && someNode.board[5] == someNode.board[8] && someNode.board[8] == 'X')
        return TRUE;
            //someNode.value = 1;//return 1;
    if(someNode.board[2] == someNode.board[5] && someNode.board[5] == someNode.board[8] && someNode.board[8] == 'O')
        return TRUE;
        //someNode.value = -1;//return -1;
    if(someNode.board[0] == someNode.board[1] && someNode.board[1] == someNode.board[2] && someNode.board[2] == 'X')
        return TRUE;
        ////someNode.value = 1;//return 1;
    if(someNode.board[0] == someNode.board[1] && someNode.board[1] == someNode.board[2] && someNode.board[2] == 'O')
        return TRUE;
        //someNode.value = -1;//return -1;
    if(someNode.board[3] == someNode.board[4] && someNode.board[4] == someNode.board[5] && someNode.board[5] == 'X')
        return TRUE;
        //someNode.value = 1;//return 1;
    if(someNode.board[3] == someNode.board[4] && someNode.board[4] == someNode.board[5] && someNode.board[5] == 'O')
        return TRUE;
        //someNode.value = -1;//return -1;
    if(someNode.board[6] == someNode.board[7] && someNode.board[7] == someNode.board[8] && someNode.board[8] == 'X')
        return TRUE;
        //someNode.value = 1;//return 1;
    if(someNode.board[6] == someNode.board[7] && someNode.board[7] == someNode.board[8] && someNode.board[8] == 'O')
        return TRUE;
        //someNode.value = -1;//return -1;
    if(someNode.board[0] == someNode.board[4] && someNode.board[4] == someNode.board[8] && someNode.board[8] == 'X')
        return TRUE;
        //someNode.value = 1;//return 1;
    if(someNode.board[0] == someNode.board[4] && someNode.board[4] == someNode.board[8] && someNode.board[8] == 'O')
        return TRUE;
        //someNode.value = -1;//return -1;
    if(someNode.board[6] == someNode.board[4] && someNode.board[4] == someNode.board[2] && someNode.board[2] == 'X')
        return TRUE;
        //someNode.value = 1;//return 1;
    if(someNode.board[6] == someNode.board[4] && someNode.board[4] == someNode.board[2] && someNode.board[2] == 'O')
        return TRUE;

    return FALSE;
}

int isTerminal(struct node someNode) {
    for(int i = 0; i < 9; i++)
        if(someNode.board[i] == ' ') // if square left to fill then game is yet incomplete
            return FALSE;
    if(someoneHasWon(someNode) == TRUE) // if any player has won earlier with squares left
        return TRUE;
    return TRUE; // if it's a draw with no squares left to fill

}

struct node nextMove(struct node someNode) {
    for(int i = 0; i < 9; i++)
        if(someNode.board[i] == ' ') {
            someNode.board[i] = 'O';
            break;
        }
        return someNode;
    }

    int minimax(struct node someNode, int depth, int maximizingPlayer) {

        if(depth == 0 || isTerminal(someNode) == TRUE) {
            if(someNode.board[0] == someNode.board[3] && someNode.board[3] == someNode.board[6] && someNode.board[6] == 'X')
                someNode.value = 1;
            if(someNode.board[0] == someNode.board[3] && someNode.board[3] == someNode.board[6] && someNode.board[6] == 'O')
                someNode.value = -1;
            if(someNode.board[1] == someNode.board[4] && someNode.board[4] == someNode.board[7] && someNode.board[7] == 'X')
                someNode.value = 1;//return 1;
            if(someNode.board[1] == someNode.board[4] && someNode.board[4] == someNode.board[7] && someNode.board[7] == 'O')
                someNode.value = -1;//return -1;
            if(someNode.board[2] == someNode.board[5] && someNode.board[5] == someNode.board[8] && someNode.board[8] == 'X')
                someNode.value = 1;//return 1;
            if(someNode.board[2] == someNode.board[5] && someNode.board[5] == someNode.board[8] && someNode.board[8] == 'O')
                someNode.value = -1;//return -1;
            if(someNode.board[0] == someNode.board[1] && someNode.board[1] == someNode.board[2] && someNode.board[2] == 'X')
                someNode.value = 1;//return 1;
            if(someNode.board[0] == someNode.board[1] && someNode.board[1] == someNode.board[2] && someNode.board[2] == 'O')
                someNode.value = -1;//return -1;
            if(someNode.board[3] == someNode.board[4] && someNode.board[4] == someNode.board[5] && someNode.board[5] == 'X')
                someNode.value = 1;//return 1;
            if(someNode.board[3] == someNode.board[4] && someNode.board[4] == someNode.board[5] && someNode.board[5] == 'O')
                someNode.value = -1;//return -1;
            if(someNode.board[6] == someNode.board[7] && someNode.board[7] == someNode.board[8] && someNode.board[8] == 'X')
                someNode.value = 1;//return 1;
            if(someNode.board[6] == someNode.board[7] && someNode.board[7] == someNode.board[8] && someNode.board[8] == 'O')
                someNode.value = -1;//return -1;
            if(someNode.board[0] == someNode.board[4] && someNode.board[4] == someNode.board[8] && someNode.board[8] == 'X')
                someNode.value = 1;//return 1;
            if(someNode.board[0] == someNode.board[4] && someNode.board[4] == someNode.board[8] && someNode.board[8] == 'O')
                someNode.value = -1;//return -1;
            if(someNode.board[6] == someNode.board[4] && someNode.board[4] == someNode.board[2] && someNode.board[2] == 'X')
                someNode.value = 1;//return 1;
            if(someNode.board[6] == someNode.board[4] && someNode.board[4] == someNode.board[2] && someNode.board[2] == 'O')
                someNode.value = -1;//return -1;
            someNode.value = 0;//return 0;
        }
        if(maximizingPlayer == TRUE) { //maximizing player is cpu i.e. 'O'

            someNode.value = NEGINF;
            while(isTerminal(someNode) != TRUE)
                someNode.value = max(someNode.value, minimax(nextMove(someNode), depth - 1, FALSE));
            return someNode.value;
    }
    else { //minimizing player is me i.e. 'X'
        int boxNumber = 0;
        scanf("%d", &boxNumber);
        someNode.position = boxNumber;
        someNode.board[someNode.position] = 'X';
        someNode.value = POSINF;
        while(isTerminal(someNode) != TRUE)
            someNode.value = min(someNode.value, minimax(nextMove(someNode), depth - 1, TRUE));
        return someNode.value;
    }
}

int main() {
    int boxNumber = 0;
    printf("Assume you're X and cpu is O \nInput any box number you like \n(0 to 8 both inclusive) \n...you'll be defeated anyways lol :\n");
    scanf("%d", &boxNumber);
    struct node origin;
    for(int i = 0; i < 9; i++)
        origin.board[i] = ' ';
    origin.position = boxNumber;
    origin.board[origin.position] = 'X';
    origin.value = 0;
    minimax(origin, 8, TRUE);
}

Code version #2 -
#include <stdio.h>
#define FALSE 0
#define TRUE 1
#define NEGINF -10000
#define POSINF +10000

struct node
{
    char board[9];
    int value;
    int position;
};

//char someNode.board[9] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '};

int max(int value, int returnedValue)
{
    return value > returnedValue ? value : returnedValue;
}

int min(int value, int returnedValue)
{
    return value < returnedValue ? value : returnedValue;
}

int someoneHasWon(struct node someNode)
{
    if (someNode.board[0] == someNode.board[3] && someNode.board[3] == someNode.board[6] && someNode.board[6] == 'x')
        return TRUE;

    if (someNode.board[0] == someNode.board[3] && someNode.board[3] == someNode.board[6] && someNode.board[6] == 'o')
        return TRUE;
    //someNode.value = -1;
    if (someNode.board[1] == someNode.board[4] && someNode.board[4] == someNode.board[7] && someNode.board[7] == 'x')
        return TRUE;
    //someNode.value = 1;//return 1;
    if (someNode.board[1] == someNode.board[4] && someNode.board[4] == someNode.board[7] && someNode.board[7] == 'o')
        return TRUE;
    //someNode.value = -1;//return -1;
    if (someNode.board[2] == someNode.board[5] && someNode.board[5] == someNode.board[8] && someNode.board[8] == 'x')
        return TRUE;
    //someNode.value = 1;//return 1;
    if (someNode.board[2] == someNode.board[5] && someNode.board[5] == someNode.board[8] && someNode.board[8] == 'o')
        return TRUE;
    //someNode.value = -1;//return -1;
    if (someNode.board[0] == someNode.board[1] && someNode.board[1] == someNode.board[2] && someNode.board[2] == 'x')
        return TRUE;
    ////someNode.value = 1;//return 1;
    if (someNode.board[0] == someNode.board[1] && someNode.board[1] == someNode.board[2] && someNode.board[2] == 'o')
        return TRUE;
    //someNode.value = -1;//return -1;
    if (someNode.board[3] == someNode.board[4] && someNode.board[4] == someNode.board[5] && someNode.board[5] == 'x')
        return TRUE;
    //someNode.value = 1;//return 1;
    if (someNode.board[3] == someNode.board[4] && someNode.board[4] == someNode.board[5] && someNode.board[5] == 'o')
        return TRUE;
    //someNode.value = -1;//return -1;
    if (someNode.board[6] == someNode.board[7] && someNode.board[7] == someNode.board[8] && someNode.board[8] == 'x')
        return TRUE;
    //someNode.value = 1;//return 1;
    if (someNode.board[6] == someNode.board[7] && someNode.board[7] == someNode.board[8] && someNode.board[8] == 'o')
        return TRUE;
    //someNode.value = -1;//return -1;
    if (someNode.board[0] == someNode.board[4] && someNode.board[4] == someNode.board[8] && someNode.board[8] == 'x')
        return TRUE;
    //someNode.value = 1;//return 1;
    if (someNode.board[0] == someNode.board[4] && someNode.board[4] == someNode.board[8] && someNode.board[8] == 'o')
        return TRUE;
    //someNode.value = -1;//return -1;
    if (someNode.board[6] == someNode.board[4] && someNode.board[4] == someNode.board[2] && someNode.board[2] == 'x')
        return TRUE;
    //someNode.value = 1;//return 1;
    if (someNode.board[6] == someNode.board[4] && someNode.board[4]

== someNode.board[2] && someNode.board[2] == 'o')
            return TRUE;

        return FALSE;
    }

    int isTerminal(struct node someNode)
    {
        for (int i = 0; i < 9; i++)
            if (someNode.board[i] == ' ') // if square left to fill then game is yet incomplete
                return FALSE;
        if (someoneHasWon(someNode) == TRUE) // if any player has won earlier with squares left
            return TRUE;
        return TRUE; // if it's a draw with no squares left to fill
    }

    struct node nextMove(struct node someNode)
    {
        for (int i = 0; i < 9; i++)
            if (someNode.board[i] == ' ')
            {
                someNode.board[i] = 'o';
                break;
            }
        return someNode;
    }

    int minimax(struct node someNode, int depth, int maximizingPlayer)
    {

        if (depth == 8 || isTerminal(someNode) == TRUE)
        {
            if (someNode.board[0] == someNode.board[3] && someNode.board[3] == someNode.board[6] && someNode.board[6] == 'x')
                someNode.value = 1;
            if (someNode.board[0] == someNode.board[3] && someNode.board[3] == someNode.board[6] && someNode.board[6] == 'o')
                someNode.value = -1;
            if (someNode.board[1] == someNode.board[4] && someNode.board[4] == someNode.board[7] && someNode.board[7] == 'x')
                someNode.value = 1; //return 1;
            if (someNode.board[1] == someNode.board[4] && someNode.board[4] == someNode.board[7] && someNode.board[7] == 'o')
                someNode.value = -1; //return -1;
            if (someNode.board[2] == someNode.board[5] && someNode.board[5] == someNode.board[8] && someNode.board[8] == 'x')
                someNode.value = 1; //return 1;
            if (someNode.board[2] == someNode.board[5] && someNode.board[5] == someNode.board[8] && someNode.board[8] == 'o')
                someNode.value = -1; //return -1;
            if (someNode.board[0] == someNode.board[1] && someNode.board[1] == someNode.board[2] && someNode.board[2] == 'x')
                someNode.value = 1; //return 1;
            if (someNode.board[0] == someNode.board[1] && someNode.board[1] == someNode.board[2] && someNode.board[2] == 'o')
                someNode.value = -1; //return -1;
            if (someNode.board[3] == someNode.board[4] && someNode.board[4] == someNode.board[5] && someNode.board[5] == 'x')
                someNode.value = 1; //return 1;
            if (someNode.board[3] == someNode.board[4] && someNode.board[4] == someNode.board[5] && someNode.board[5] == 'o')
                someNode.value = -1; //return -1;
            if (someNode.board[6] == someNode.board[7] && someNode.board[7] == someNode.board[8] && someNode.board[8] == 'x')
                someNode.value = 1; //return 1;
            if (someNode.board[6] == someNode.board[7] && someNode.board[7] == someNode.board[8] && someNode.board[8] == 'o')
                someNode.value = -1; //return -1;
            if (someNode.board[0] == someNode.board[4] && someNode.board[4] == someNode.board[8] && someNode.board[8] == 'x')
                someNode.value = 1; //return 1;
            if (someNode.board[0] == someNode.board[4] && someNode.board[4] == someNode.board[8] && someNode.board[8] == 'o')

         someNode.value = -1; //return -1;
        if (someNode.board[6] == someNode.board[4] && someNode.board[4] == someNode.board[2] && someNode.board[2] == 'x')
            someNode.value = 1; //return 1;
        if (someNode.board[6] == someNode.board[4] && someNode.board[4] == someNode.board[2] && someNode.board[2] == 'o')
            someNode.value = -1; //return -1;
        someNode.value = 0;      //return 0;
    }
    if (maximizingPlayer == TRUE)
    { //maximizing player is cpu i.e. 'o'

        someNode.value = NEGINF;
        while (isTerminal(someNode) != TRUE)
            someNode.value = max(someNode.value, minimax(nextMove(someNode), depth + 1, FALSE));
        if (someNode.value == -1) {
            printf("o %d \n", someNode.value);
            return someNode.value;
        }
    }
    else
    { //minimizing player is me i.e. 'x'
        int boxNumber = 0;
        printf("Enter your move :\n");
        scanf("%d", &boxNumber);
        someNode.position = boxNumber;
        someNode.board[someNode.position] = 'x';
        someNode.value = POSINF;
        while (isTerminal(someNode) != TRUE)
            someNode.value = min(someNode.value, minimax(nextMove(someNode), depth + 1, TRUE));
        if (someNode.value == 1)
            return someNode.value;
    }
}

int main()
{
    int boxNumber = 0;
    printf("Assume you're x and cpu is O \nInput any box number you like \n(0 to 8 both inclusive) \n...you'll be defeated anyways lol :\n");
    scanf("%d", &boxNumber);
    struct node origin;
    origin.position = boxNumber;
    origin.board[origin.position] = 'x';
    origin.value = 0;
    printf("%c %d \n", origin.board[origin.position], origin.position);
    int val = minimax(origin, 1, TRUE);
    if(val > 0)
        printf("You lose");
    else if(val < 0)
        printf("You win");
    else
        printf("It's a draw");
    return 0;
}

A:
What I think is that I'm missing a function that actually makes use of the returned 'scores'.

Well, no, the the minimax() function itself is the only one that needs the score it (recursively) computes.  The issue is that the pseudocode you're looking at on Wikipedia is very "pseudo".  It illustrates the idea of the algorithm reasonably well, but it doesn't provide a very good model for actually implementing it.  In particular, it omits a key component that any practical implementation requires: in addition to computing a score, minimax() needs to provide at least one move that leads to that score.  That's the move the top-level caller chooses.

Also the nextMove() function confuses me, I want it to check if there is no unfilled box, then fill it with 'O' and then it's the player's turn. But since it will be called again in the recursion, it might not work correctly. Any suggestions?

There are at least two possible general approaches:

*

*make temporary copies of the board as needed, so that you can modify these without changing the original, or

*keep track of each position tested, and clear it after the test.

Either way, it's helpful to separate the move analysis process from the actual choice of move.
Note well that you are already making copies by passing struct node objects by value. By itself, that's not necessarily a full or correct implementation of option (1), but it's definitely something to be aware of, especially with respect to my main point, above.
Also, I don't particularly like the pseudocode's approach of using a boolean input to minimax() to indicate whether to maximize or minimize.  I prefer instead to pass an argument to indicate which player's move it is.  In a symmetric game such as Tic Tac Toe, the minimax() function then makes use of the fact that the better a result is for one player, the worse it is for the other.  Among other things, this tends to simplify the code because the code then doesn't need separate cases around the value of that parameter.

A: Tic-tac-toe is a very simple game, so thus doesn't have too many game-states. So you do not need to limit the AI to a depth.
function bestMove(board, maximisingPlayer) is
  if tie then
    return {value: 0}
  else if maximising player won then
    return {value: ∞}
  else if minimising player won then
    return {value: -∞}

  if maximisingPlayer then
    value := -∞
    move := 0

    for each child of node do
      tempValue := minimax(child, FALSE).value

      if tempValue > value then
        value := tempValue
        move := child

    return {value: value, move: move}
  else
    value := ∞
    move := 0

    for each child of node do
      tempValue := minimax(child, TRUE).value

      if tempValue < value then
        value := tempValue
        move := child

    return {value: value, move: move}

/* Returns best child node after move is made. */
currentBestMove := bestMove(currentBoard, currentPlayer).move

Also as a remark on your code, do not put the win logic in the same procedure as the minimax, try to split your code into smaller functions as much as possible. Also, you may store the win combinations in an array.


text:
Q: Mostrar termos de uma taxonomia aleatoriamente Eu estou exibindo todas as categorias com suas respectivas imagens, conforme o código abaixo:
<?php
categorias = apply_filters('taxonomy-images-get-terms', '', array( 'taxonomy' => 'category') );
foreach($categorias as $key => $categoria):
    if($key < 6):
    ?>

        <a href="<?php echo get_category_link($categoria->term_id);?>">

                <?php echo wp_get_attachment_image($categoria->image_id,''); ?>

            <img src="<?php bloginfo('template_directory');?>/images/icones/plus.png" class="plus-icone" alt="">

<?php echo $categoria->name;?>

    <?php
    endif;
endforeach;?>

Foi usado a função apply_filters para poder exibir a imagem da categoria, até onde eu consegui achar na internet só dessa forma que é possível fazer isso. Pelo que notei essa função mostra todos os resultados em ordem alfabética e eu preciso mostra-los aleatoriamente ou por data.
É possível fazer isso?

A: Ao que parece apply_filters está sempre retornando um array ali, então basta reordenar o array usando shuffle pra ficar embaralhado:
$categorias = apply_filters('taxonomy-images-get-terms', '', array( 'taxonomy' => 'category') );

shuffle( $categorias );

foreach ( $categorias as $key => $categoria ) : //etc

redpajama_set_name: RedPajamaStackExchange


text:
Q: Suppressing pivot items in a pivot chart I have created a pivot table that lists the number of visitors to a store on a given date. There are 3 columns of data, the date column and two columns of numbers representing the visitors. When I create a chart from this data I get a bar of data that represents dates before and after the range of dates that make up the data. I can suppress all dates that occur prior to the dates I want to view by using the command:
With Worksheets("Pivot Tables").PivotTables("Weekly Statistics").PivotFields("Date")
    .PivotItems.Item(1).Visible = False

However, I can't find a way to suppress the dates that occur after today's date. This leaves me with a column on my bar chart that is blank and has the axis value ">3/27/2013". I can suppress it by actually typing this line:
    .PivotItems.Item(">3/27/2013").Visible = False

but having to manually do this every time I update the sheet is laborious and makes the sheet unusable to anyone else.
I tried to create a variable that would update the value inside the () but I can't get it to work.
     Dim t
     t = Worksheets("Data").Range("i3").Value
     .PivotItems.Item(t).Visible = False

(where i3 is a cell in the Worksheet("Data") that is a concatenation of the date; in this case the cell contents are ">3/27/2013" )
Thanks

A: You could try to use alternative filtering technique:
t="3/27/2013"
Worksheets("Pivot Tables").PivotTables("Weekly Statistics").PivotFields("Date").PivotFilters.Add Type:=xlBefore, Value1:=t

However, it is used as of Excel 2007.
If not working try to start with:
    Worksheets("Pivot Tables").PivotTables("Weekly Statistics").PivotFields("Date").ClearAllFilters


text:
Q: What drives SE's high international user engagement? For a company based in New York, founded by two Americans, I see more international user activity on Stack Exchange than most other American websites.  Specifically, I encounter what seems to be a disproportionately high amount of international content on Sports and Motor Vehicle Maintenance and Repair than I've experienced at other social or user-engaged websites.
For the Sports page, Cricket and football are both higher-ranking tags than any of the big four American sports.  A large portion of the questions specifically address cricket and association football.
Though the Motor Vehicle Maintenance and Repair page doesn't have any outstandingly international tags as a tangible example, I'll reference my experiences.  I've seen more international verbiage on this site than any other automotive forum or Q&A arena (bonnet, tyre, petrol, etc.).  I've also seen many references to vehicle models and trim levels that do not exist in the US, again, more than I have in my time in other automotive websites.

A: It all boils down to the way they have grown through time.
StackOverflow was a huge hit. So, it's incredibly huge amount of users is justifiable.
The way moderation is done in the SE sites deserve much of the credit. The quality of the posts in most sites are so good, that they pop up in the top search results for most buzz words, and common phrases.
Many sites are slowly turning into dumps of clutter, without proper moderation. Having been a very early adopter of Quora, I feel very sad to say that my time spent on Quora is slowly decreasing, as the site accumulates more and more unmoderated clutter.
For example, I am a data scientist in India. I had a doubt in statistics, which bugged me a lot. I typed the relevant words from the doubt on Google. Then, I stumbled upon CrossValidated, the stats site of SO.
That was the first time I realized there were other sites in the network, apart from just SO. And, I also got my doubt cleared, both from the post and from the chat. (User Onboarding succesfully done)
Now, the site should try and retain me as a long-time user, which is the most difficult part. And that is excellently being done by the way the sites are moderated. I enjoyed myself at CV, both on chat and answering questions. (User Retention succesfully done)
My curiosity got the better of me, and I started wandering into a lot of other site, like WorkPlace, SFF (<-- being a huge HP fan myself), etc. I enjoyed my time in almost all of them. Thus I became a promoter of SO (the result being this answer).
So, SO has a similar user conversion journey like most startups, and is consistently polishing it.

A: I think one reason is the collaborative nature of the sites. If someone who speaks (writes) English as a second language asks a question on a site, and someone else cleans up the English, they end up getting an answer. Maybe some upvotes too. They feel welcome. If one site works for them, there's a good confidence another site in the network, with the same mechanics, will work too.
Also, plenty of sites draw moderators from around the world for practical reasons related to time zones. But a natural side effect is that people from around the world are likely to feel represented and included in a way that the phrase "a company based in New York, founded by two Americans" wouldn't naturally evoke.


text:
Q: How to make this piece of code more efficient (KS Test) My data look like these
id1,id2,similarity
CHEMBL1,CHEMBL1,1
CHEMBL2,CHEMBL1,0.18
CHEMBL3,CHEMBL1,0.56
CHEMBL4,CHEMBL1,0.64
CHEMBL5,CHEMBL1,0.12
CHEMBL1,CHEMBL2,0.18
CHEMBL2,CHEMBL2,1
CHEMBL3,CHEMBL2,0.26
CHEMBL4,CHEMBL2,0.78
CHEMBL5,CHEMBL2,0.33
CHEMBL1,CHEMBL3,0.56
CHEMBL2,CHEMBL3,0.26
CHEMBL3,CHEMBL3,1
CHEMBL4,CHEMBL3,0.04
CHEMBL5,CHEMBL3,0.85
CHEMBL1,CHEMBL4,0.64
CHEMBL2,CHEMBL4,0.78
CHEMBL3,CHEMBL4,0.04
CHEMBL4,CHEMBL4,1
CHEMBL5,CHEMBL4,0.49
CHEMBL1,CHEMBL5,12
CHEMBL2,CHEMBL5,0.33
CHEMBL3,CHEMBL5,0.85
CHEMBL4,CHEMBL5,0.49
CHEMBL5,CHEMBL5,1

The whole file is around 197million lines (10GB). My goal is to compare the distributions of column 3 for each compound in column 1. With a lot of refactoring I managed to have this piece of code
import pandas as pd
from scipy.stats import ks_2samp
import re

with open('example.csv', 'r') as f, open('Metrics.tsv', 'a') as f_out:
    f_out.write('compound_1' + '\t' + 'compound_2' + '\t' + 'Similarity' + '\t' + 'KS Distance' + '\n')
    df = pd.read_csv(f, delimiter = ',', lineterminator = '\n', header = None)
    d = {}
    l_id1 = []
    l_id2 = []
    l_sim = []
    uniq_comps = df.iloc[:, 0].unique().tolist()
    for i in uniq_comps:
        d[i] = []
    for j in range(df.shape[0]):
        d[df.iloc[j, 0]].append(df.iloc[j, 2])
        l_id1.append(df.iloc[j, 0])
        l_id2.append(df.iloc[j, 1])
        l_sim.append(df.iloc[j, 2])
    for k in range(len(l_id1)):
        sim = round(l_sim[k]*100, 0)/100
        ks = re.findall(r"statistic=(.*)\,.*$", str(ks_2samp(d[l_id1[k]], d[l_id2[k]])))
        f_out.write(l_id1[k] + '\t' + l_id2[k] + '\t' + str(sim) + '\t' + str(''.join(ks)) + '\n')

which runs but as expected is extremely slow. Does anyone have any ideas of how it could be made faster? My desired output looks like this
 compound_1,compound_2,Similarity,KS Distance
CHEMBL1,CHEMBL1,1.0,0.0
CHEMBL2,CHEMBL1,0.18,0.4
CHEMBL3,CHEMBL1,0.56,0.2
CHEMBL4,CHEMBL1,0.64,0.2
CHEMBL5,CHEMBL1,0.12,0.4
CHEMBL1,CHEMBL2,0.18,0.4
CHEMBL2,CHEMBL2,1.0,0.0
CHEMBL3,CHEMBL2,0.26,0.2
CHEMBL4,CHEMBL2,0.78,0.4
CHEMBL5,CHEMBL2,0.33,0.2
CHEMBL1,CHEMBL3,0.56,0.2
CHEMBL2,CHEMBL3,0.26,0.2
CHEMBL3,CHEMBL3,1.0,0.0
CHEMBL4,CHEMBL3,0.04,0.2
CHEMBL5,CHEMBL3,0.85,0.2
CHEMBL1,CHEMBL4,0.64,0.2
CHEMBL2,CHEMBL4,0.78,0.4
CHEMBL3,CHEMBL4,0.04,0.2
CHEMBL4,CHEMBL4,1.0,0.0
CHEMBL5,CHEMBL4,0.49,0.2
CHEMBL1,CHEMBL5,12.0,0.4
CHEMBL2,CHEMBL5,0.33,0.2
CHEMBL3,CHEMBL5,0.85,0.2
CHEMBL4,CHEMBL5,0.49,0.2
CHEMBL5,CHEMBL5,1.0,0.0

Would it be wiser to run it in Pyspark due to the size of the data? If so, how could a similar effect be achieved?

A: Code check
There are some key points that should be highlighted and may improve the performance:

*

*You already have all the data loaded in RAM as you opened the CSV in pandas, then it is not necessary to have copy of that data into lists (eg. l_id1, l_id2, etc.). Avoid whenever possible having multiple copies of data, it undermines performance and makes code harder to debug.

*When dealing with Pandas DataFrame, try to avoid writing explicit loops as often as possible, there should have a method that does it for you, such as groupby.

*Scipy statistic package returns a Result object which always exposes statistic and pvalue member, use it instead of casting into string and then extract value using regular expression.

*Avoid unnecessary call to expensive function, in the last loop you compute a lot of time the same quantity for the Two Sample KS Test, instead compute each once and merge results with dataset afterward.

Refactoring
As you seems to be able to open the CSV using pandas, I will assume the complete file fit in your memory. Checking twice, numerical data should fit in 2Gb of RAM.
8 bytes*197e6 rows/1024**3 ~ 1.47 Gb

It is not clear what you want to compute. I will assume you want to collect data based on the id1 column, then you want to check if distribution are equivalent using the Two Sample Kolmogorov-Smirnow test based on each possible pair of identifiers. If this is not what you want to do, please update your post to detail what you intend to compute.
Let's create a trial DataFrame:
import itertools
import numpy as np
import pandas as pd
from scipy import stats

N = 10**6
df = pd.DataFrame({
    "id1": np.random.choice([f"CHEMBL{i:d}" for i in np.arange(1, 6)], N),
    "id2": np.random.choice([f"CHEMBL{i:d}" for i in np.arange(1, 6)], N),
    "value": np.random.uniform(0, 12, N)
})

The trial dataset looks like:
       id1      id2      value
0  CHEMBL4  CHEMBL3  10.719870
1  CHEMBL2  CHEMBL5   2.911339
2  CHEMBL4  CHEMBL4   0.001595
3  CHEMBL2  CHEMBL3   0.148120
4  CHEMBL5  CHEMBL2   4.683689

Once the DataFrame is created, it is easy to group data by identifier using groupby method. Then we can apply a statistical test on all possible pairs of identifier. If we assemble everything in a generator, it is about:
def apply_test(df, idkey="id", valuekey="value", test=stats.ks_2samp):
    """
    Apply statistical test to each possible pair of identifier
    """
    # Group by identifier:
    g = df.groupby(idkey)
    # Generate all 2-combination of identifier:
    for k1, k2 in itertools.combinations(g.groups.keys(), 2):
        # Apply Statistical Test to grouped data:
        t = test(df.loc[g.groups[k1],valuekey], df.loc[g.groups[k2],valuekey])
        # Store Identifier pair:
        res = {"id1": k1, "id2": k2}
        # Store statistics and p-value:
        res.update({k: getattr(t, k) for k in t._fields})
        # Yield result:
        yield res

At this point, just apply the function on the dataframe:
r = pd.DataFrame([x for x in apply_test(df)])

It returns for the trial dataset:
       id1      id2  statistic    pvalue
0  CHEMBL1  CHEMBL2   0.002312  0.657859
1  CHEMBL1  CHEMBL3   0.002125  0.756018
2  CHEMBL1  CHEMBL4   0.001701  0.934290
3  CHEMBL1  CHEMBL5   0.002560  0.527594
4  CHEMBL2  CHEMBL3   0.002155  0.741524
5  CHEMBL2  CHEMBL4   0.001766  0.914602
6  CHEMBL2  CHEMBL5   0.003035  0.315677
7  CHEMBL3  CHEMBL4   0.001668  0.944053
8  CHEMBL3  CHEMBL5   0.002603  0.507482
9  CHEMBL4  CHEMBL5   0.002661  0.479805

Then we can merge those results with the original dataframe:
df.merge(r)

            id1      id2      value  statistic    pvalue
0       CHEMBL2  CHEMBL5   2.911339   0.003035  0.315677
1       CHEMBL2  CHEMBL5   6.583948   0.003035  0.315677
2       CHEMBL2  CHEMBL5  10.237092   0.003035  0.315677
3       CHEMBL2  CHEMBL5   8.049175   0.003035  0.315677
4       CHEMBL2  CHEMBL5   3.977925   0.003035  0.315677
...         ...      ...        ...        ...       ...
400776  CHEMBL4  CHEMBL5   4.339528   0.002661  0.479805
400777  CHEMBL4  CHEMBL5   5.353133   0.002661  0.479805
400778  CHEMBL4  CHEMBL5  10.599985   0.002661  0.479805
400779  CHEMBL4  CHEMBL5   9.701375   0.002661  0.479805
400780  CHEMBL4  CHEMBL5   7.951454   0.002661  0.479805


text:
Q: Requiring files in the Volt Framework I have a mixin I want to include in a few different classes in a Volt app. Pertinent structure as follows:
Including file path: app/component_1/models/my_model.rb
Included file path: app/component_2/mixins/my_mixin.rb
Here's what I've tried:
require "#{Volt.root}/app/component_2/mixins/my_mixin" yields this error in the server output when loading a page: SyntaxError: Cannot handle dynamic require
require "app/component_2/mixins/my_mixin" yields this error when starting the server: in `require': cannot load such file
require_relative "../../component_2/mixins/my_mixin" yields this error in the server output when loading a page: Opal::Builder::MissingRequire: A file required by "app.rb" wasn't found. can't find file: "../../component_2/mixins/my_mixin"
require "./app/component_2/mixins/my_mixin" yields this error in the javascript console when loading a page: Uncaught RuntimeError: no routes match path: /
Not sure what else to try?

A: Sorry this is unclear, I'll try and update the docs to make it easier.  So the app folder is what's on the load path.  So you can require from there.
require 'component_2/mixings/my_mixin'


text:
Q: @Override for interface methods causes JSP compilation to fail For some reason, putting @Override on methods overriding interface methods causes JSP compilation to fail in weblogic. Everything is definitely running off of JDK 1.6.0_14, but this Java 5'ism still persists.
Oddly, JSP compilation occasionally fails with a stacktrace pointing at code not necessarily obviously used by the JSP itself.
What's going on here?

A: I've seen this a lot myself. In Java 6, it is (supposedly) permissible to use @Override on interface implementation methods. In Java 5, this is an error. However in my Java 6 code, sometimes @Override is accepted on interface implementation methods, and sometimes it is not.
To make things weirder, some IDEs (e.g. NetBeans) are fine with it, while IntelliJ IDEA is sometimes ok and sometimes not. I have found, however, that compiling the code in either IDE will ignore the alleged errors being reported by the IDE.
In other words, is the problem manifesting in your IDE? If so, compile the code directly (use the command-line if necessary) and see what happens. The IDE may be reporting spurious errors.

A: The @Override is supposed to only be retained in source so shouldn't come up in byte code.  There might an angle you can play in ensuring those classes are complied separately from the JSPs and simply available in the classpath -- rather than the source path.
If that's already the case then it might be a different issue than what is immediately showing.
Used to be the JSP complier was a separate library shipped with the server and not tied to the vm the server is running in.  WLS used to use Javelin.  Seems like they switched that in 10 to use the Java Compiler API.  So it should work fine as long as you have Sun vm Java 1.6.  But if there's 'javelin' anything in your stacktrace, definitely check that angle.

A: A possible workaround might be to precompile JSP using appc. This could at least allow to circumvent the issue.
Regarding the "real" question, my understanding is that you did upgrade domains, so maybe have a look at the following resources:

*

*Web Applications, JSPs, and Servlets

*

*Backwards Compatibility Flags

*Procedure for Upgrading a WebLogic Domain

*

*Select Upgrade Options (related to domain upgrade)

*Backward Compatibility Flags

*

*JSPCompilerBackwardsCompatible - Specifies whether to allow JSPs that do not comply with the JSP 2.0 specification

This is a wild guess but maybe some backward compatibility flag is activated and WebLogic keeps using the "old" approach.

A: I agree with your instinct and the other answers that WLS is using Java 5 somehere.  The items below seem like useful tidbits from Oracle/WebLogic resources.  I don't have a WebLogic  Server 10.3 installation to confirm these:
Weblogic Server 10.3
According to this, at least Weblogic Server 10.3 is required to use Java 6, but I can't see anything the confirms this as authoritative info:

*

*http://forums.oracle.com/forums/thread.jspa?threadID=884263

Re: WebLogic 10.0 supports Java 6?
  Posted: Apr 9, 2009 12:26 PM     in response to: user8324142
  Hi,
  Weblogic 10 will not support JDK6.
  Please upgrade to Weblogic 10.3 to work with JDK 6.

Checking the Java version

*

*http://download.oracle.com/docs/cd/E12840_01/common/docs103/install/postins.html#wp1090736

Determining Which JDK Version You Are Using
You can determine which version of the JDK you are using by issuing a command, as follows:

*

*Open a command prompt window and go to the appropriate directory:
  BEA_HOME\WL_HOME\server\bin (Windows)
  BEA_HOME/WL_HOME/server/bin (UNIX)
In both pathnames, BEA_HOME represents the directory in which you have installed your software and WL_HOME represents the wlserver_< version >.

*Make sure that your environment is set up properly by entering the following command at the prompt:
  setWLSenv.cmd (Windows)
  setWLSenv.sh (UNIX)

*Enter the following command at the prompt:
  java -version

Configuring Java version:

*

*http://download.oracle.com/docs/cd/E12840_01/wls/docs103/perform/WLSTuning.html

Setting Java Parameters for Starting WebLogic Server
... Java parameters must be specified whenever you start WebLogic Server. ... Oracle recommends that you incorporate the command into a [startup] script ...
If you used the Configuration Wizard to create your domain, the WebLogic startup scripts are located in the domain-name directory where you specified your domain. By default, this directory is BEA_HOME\user_projects\domain\domain-name, where BEA_HOME is the directory that contains the product installation, and domain-name is the name of the domain directory defined by the selected configuration template. ...
Change the value of the variable JAVA_HOME to the location of your JDK. For example:
set JAVA_HOME=C:\bea\jdk150_03
...

A: In my mind, @Override makes sense on methods that are overriding methods, not implementing methods.
So if you have an interface:
public interface MyInterface {
    public void doSomething();
}

A class that implements that interface is below (MyClassA):
public MyClassA implements MyInterface {
    public void doSomething() {
        System.out.println("This is from MyClassA");
    }
}

Then, the below class extends MyClassA and overrides doSomething, and so then I'd add the @Override annotation.
public MyClassB extends MyClassA implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("This is from MyClassB");
    }
}

I wouldn't do the below (whether or not it is permissable) in any case, since it breaks the idea about overriding something - you're implementing, not overriding the interface:
public MyClassA implements MyInterface {
    @Override
    public void doSomething() {
        System.out.println("This is from MyClassA");
    }
}


text:
Q: Disable Button and change button text on click after ajax success function call I am working on PHP ajax project. I want to disable and change the button's text after the success function call in ajax. my ajax function is working fine and I am getting the desired output. just one thing is remaining which is the button thing.
Here is my code for ajax.
 $(document).ready(function () {

  $(document).on("click", "#add_btn", function (e) {
    e.preventDefault();
    var id = $(this).val();
    var cus_id = $('#customer_selection').val();
    if (!cus_id) {
      alert("Please select a customer")

    } else {

      $.ajax({
        url: "add_selection_script.php",
        type: "POST",
        data: {
          id: id,
          cus_id: cus_id
        },
        success: function (data) {
          // here i want to change button text and disable for click button only
            not others because my buttons are dynamic
          prop("disabled", true);
          html("Added");

        }
      });
    }
  });
});

here is the button code
<button type="submit" id="add_btn" value="<? echo $id; ?>">Add to selection</button>

A: you have to give identifier for which you have to make changes
$("#add_btn").prop('disabled', true);
$("#add_btn").html('Added');

if your button is dynamic, then you can do below:
on click of button, get your element in a variable
var element = $(this);

and in your success function, write this
element.prop('disabled', true);
element.html('Added');

A: You need to set the attribute of the button and use .html or .text to change the text.
success: function (data) {
  $('#add_btn').attr('disabled', true);
  $('#add_btn').html('changed text');
}


text:
Q: The element nav-item dropdown not working in laravel vue Im using laravel and vue js also Adminlte
In the beginning it was working but now ....
head

<link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">

  <link rel="stylesheet" href="dist/css/adminlte.min.css">

  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">

nav

      Cerrar sesión

        <form action="{{route('logout')}}" method="POST">
          {{ csrf_field() }}
          Usuario
          <button type="submit" class="float-right text-muted text-sm"> Salir  </button>
        </form>

scripts

it shows me: DevTools failed to parse SourceMap: http://x.x.x.x:8000/js/popper.js.map
data-toggle="dropdown" does not show the elements
in components app.js
require('./bootstrap');

require('./components/Example');

import Multiselect from 'vue-multiselect';

Vue.component('multiselect', Multiselect);

The problem comes when i used npm run dev the app.js generated makes it doesn work, any idea

A: I had a same problem. The reason which causes this is AdminLTE template and Vue.js also includes Bootstrap and they collide. So you have to comment out or delete the Bootstrap 4 script tag, this line:

This line is already redundant.


text:
Q: Invoke self hosted WCF from jQuery not working I have a self hosted WCF through a windows service. I am trying to call a method in service but its not working. I can see following error in google chrome console

OPTIONS http://localhost:9093/Service1/method1
XMLHttpRequest cannot load http://localhost:9093/Service1/method1. Invalid HTTP status code 400

this is my jQuery code
var url = 'http://localhost:9093/Service1/method1';
                $.ajax({
                    url: url,
                    data: { identifire: identifire },
                    type: 'POST',
                    global: false,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: callbacks.success,
                    error: function () { }
                })

here is my contract
[OperationContract]
        [WebInvoke(Method = "POST",
            BodyStyle = WebMessageBodyStyle.Wrapped,
            ResponseFormat = WebMessageFormat.Json)]
        void method1(string identifire);

here is the config file
 <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webSupport">
          <webHttp />

        </behavior>
      </endpointBehaviors>
    </behaviors>

    <services>
      <service name="IService1" behaviorConfiguration="ServiceBehavior">
        <endpoint address="http://localhost:9093/Service1" behaviorConfiguration="webSupport"
            binding="webHttpBinding" bindingConfiguration="" contract="IService1" />
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>

</configuration>

this is how I start my service inside OnStart event of my windows service
string hostAddress = "http://localhost:9093/Service1";

        Uri[] addresses = { new Uri(hostAddress) };

        scanHost = new ServiceHost(typeof(Service1),addresses);
        scanHost.Open();

BTW when I invoke this method using a Service reference from ASP.net it works fine. I only get issues when trying to call this from jQuery

A: Change your endpoint tag like this
<endpoint address="" behaviorConfiguration="webSupport"
        binding="webHttpBinding" bindingConfiguration="" contract="IService1" />

Also your url should be like this
var url = 'http://localhost:9093/Service1.svc/method1';

And data should be like this
data: JSON.stringify({identifire: identifire}),


text:
Q: Transformations.switchMap проблема На официальном сайте Android
Имеется код, который позволяет получать данные по изменяемому полю
MutableLiveData userIdLiveData = ...;
 LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
     repository.getUserById(id));

 void setUserId(String userId) {
      this.userIdLiveData.setValue(userId);
 }

Я хочу изменять, вводя поисковый запрос в SearchView.
Для этого у меня есть соответствующая переменная, и метод, который я буду дергать, при изменении текста в SearchView
private val query = mutableLiveData("")
fun handleSearchQuery(text: String?) {
        query.value = text
}

fun <T> mutableLiveData(defaultValue: T? = null): MutableLiveData<T>{
    val data = MutableLiveData<T>()

    if(defaultValue != null){
        data.value = defaultValue
    }

    return data
}

Но я не могу дописать его, кидает ошибки, он не видит trackName
private var songs : LiveData<Result<List<Song>>> = Transformations.switchMap(query, trackName ->
            getSongsBySearch(trackName))

private fun getSongsBySearch(searchQuery: String): LiveData<Result<List<Song>>>{
        return repository.getSongBySearchAlbumTerm(searchQuery)}

Нашел вот такой пример
private val query = MutableLiveData<String>()
    private val userRepo = UserRepo()
    val userNameResult: LiveData<List<User>> = Transformations.map(
            query,
            ::temp
    )
    private fun temp(name: String) = userRepo.searchUserWithName(name)

Но у меня не видит метод, когда я пытаюсь вставить вместо ::temp


text:
Q: Datetime parameter in PHP SOAP call using the SoapClient class I've developed a PHP SOAP call with code bellow with datetime parameter.
Problem is that it displays "No Items found" if there is only one item, after the given time.
When i make the call for longer period, it shows all items accordinly.

Blockquote

Current DateTime is : 02-18-2020 13:46:20
Display products after DateTime : 02-18-2020 13:40:00
No Items found
No Items found
No Items found
...........
Thanks in advance for the help.
 <?php

echo "Current DateTime is : " . date("m-d-Y H:i:s") . "

";
// $dateTime = date('m-d-Y H:i:s',strtotime('-40 minutes'));

$dateTimeCall = '02-18-2020 13:40:00' ;

echo "Display products after DateTime : " . "" . $dateTime . "" .    "

";

$soap_client = new SoapClient('http://.......    /eCommerceWebService.asmx?WSDL') ;
$params = array('SiteKey' => 'qwerty',
            'Date' => $dateTimeCall,
            'StorageCode' => '11111' ) ;

 //     GetProducts
 $response = $soap_client->GetProducts($params) ;
 $all_products = $response->GetProductsResult->StoreDetails ;

 foreach( $all_products as $product ) {

$ItemId = $product->ItemId;
$model = $product->ItemCode;
$ItemDateModified = $product->ItemDateModified;

// echo $ItemId . " - " . $model . " - " . $ItemDateModified . "
";

$date = date_create($ItemDateModified);
$dateTime = date_format($date, 'm-d-Y H:i:s');

if ($ItemId) {
echo $ItemId . " - " . $model . " - " . $dateTime . "
";
}
else {
echo "No Items found " . "
";
}
}

 ?>


text:
Q: Responsive Design Mode on desktop does not behave the same on the actual device I am having a frustrating CSS problem. I am building a a single page JS map application and am trying to synchronize styles across browsers/devices. I thought I did a successful job using Responsive Design Mode in Safari/Firefox. It looks the same to me when I switch between iPad/Galaxy/iPhone/desktop in the browser emulator.
However, when I actually open the page on my phone in Firefox/Safari, it does not appear the same. Specifically, the ? button is wider than the rest of the buttons below it. I specifically have the width property explicitly set to 40 pixels in the CSS.
What is happening here? Why is the ? button wider?
Here are some screenshots of what I mean:
Desktop
Desktop/Responsive Mode iPad
Desktop/Responsive Mode iPhone
My actual iPhone
I tried connecting my phone using Remote Debug but I don't really know how to use it without visualizing the actual phone screen so I can't see what I'm editing. Anyone have any ideas?

A: I found the problem. For some reason, padding was being added in iPhone and not in responsive mode or other browsers. Adding padding:0 to the button fixed the problem.


text:
Q: Regex check if there is a splitter character between all elements I've got a regex that I'm trying to use to detect if a certain input is valid. The syntax of the input should be {A|B|C}. {A|B|} should fail.
(?:
 (
  \{{1}
  (?:[A-Z0-1-_.*]+ \| [A-Z0-1-_.*]+)*
  \}{1}
 )
)

This is what I have so far, but I'm starting to think this isn't the way to go. Even if it did work properly, it wouldn't allow {A} which should be valid.
So basically what I'm trying to do is check if each [A-Z0-1-_.*] element is split by | and that there are no empty elements within the {} brackets.
One concept I'm really struggling with which feels relevant here is having n amount of possible elements. Like let's say, the string to validate is Foo{A}Bar{B|C}Test
The way I would check that has 2 elements. One element to check for alphabetical characters, and another element to check the bracketed characters.
So to check the string above, I would do alphaElem*|BracketElem*|alphaElem*|BracketElem*|alphaElem*
But that's a lot of writing out, and it doesn't scale if the amount of elements increases. Is there some way I can solve this with regex?

A: You may use
{[A-Z0-1-_.*]+(?:\|[A-Z0-1-_.*]+)*}

Note that the last * modifier can be replaced with a limiting quantifier. E.g. {0,2} to match 0, 1 or 2 times (to match 1, 2 or 3 elements inside {...}).
See the regex demo.
Details

*

*{ - a { char

*[A-Z0-1-_.*]+ - 1 or more chars defined in the character class (uppercase ASCII letters, 0, 1, -, _, . or * chars)

*(?: - a non-capturing group matching  0 or more occurrences of:

*

*\| - a | char

*[A-Z0-1-_.*]+ - 1 or more chars defined in the character class

*)*  - end of the grouping construct

*} - a } char.

Note you do not need to escape { and } chars in a .NET regex, it is "intelligent" enough to parse { as a literal { if there is no matching } with min or min,max values before.

A: This solution will validate everything you (seem to) want in one pass (see on
regex101):
^\w+({[A-Z0-1-_.*]+(\|[A-Z0-1-_.*]+)*}\w+)*$
It's several layers of possibly-repeating sections.
Here's the breakdown:
^ anchor matching start of text
\w+ matches any amount of "word" characters
{[A-Z0-1-_.*]+(\|[A-Z0-1-_.*]+)*} matches an element in brackets, possibly followed by any number of pipes and other elements within the brackets
({[A-Z0-1-_.*]+(\|[A-Z0-1-_.*]+)*}\w+)* this is the previously-described match, allowed to repeat zero to many times, each time with another "word"
$ anchor matching end of text


text:
Q: How do I configure my media files to upload on AWS S3 Bucket in Django? I've created a Blogging App using Django and Heroku-Postgres as Database. The user uploaded images gets removed in Heroku-Postgres after redeployment I think and it just disappears from the website.
I tried fixing this using AWS S3 Bucket but I'm not able to configure the settings in my Django App, the user uploaded files are uploaded to media/images/ according to my models.py
models.py
    class Post(models.Model):
        title = models.CharField(max_length=255)
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        article_image = models.ImageField(null=True, blank=True, upload_to="images/")

settings.py
    AWS_STORAGE_BUCKET_NAME = '#####'
    AWS_S3_REGION_NAME = 'us-east-1'
    AWS_ACCESS_KEY_ID = '####'
    AWS_SECRET_ACCESS_KEY = '####'

    AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
    MEDIAFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'

    STATIC_URL = '/static/'
    # STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    STATICFILES_DIRS = [
       os.path.join(BASE_DIR, 'static'),
    ]
    DISABLE_COLLECTSTATIC=1

    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Now, what am I supposed to remove/keep from these so that the user uploaded images which are now stored in media/images/ are stored in AWS S3 Bucket?


text:
Q: Need to get body from HttpObjectAggregator.AggregatedFullHttpRequest in Netty I am using a configurable proxy(little proxy) to listen on requests generated from client end i.e chrome browser. I need the body of the post request.
In the pipeline, this is the one i added. I thought i will be getting a FullHttpRequest, but getting
pipeline.addLast("decoder", new HttpRequestDecoder(8192*4, 8192 * 8,8192 * 8));
pipeline.addLast("inflater", new HttpContentDecompressor());
pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
pipeline.addLast("encoder", new HttpResponseEncoder());

For Post request, I am getting this data type HttpObjectAggregator#AggregatedFullHttpRequest. I tried debugging. But not able to understand the concept of compositebytebuff.
Let me know how to achieve this.

A: Found the issue. I thought the error thrown was due to some bytebuf issue. It was because, when i listen for request, i get the original request and send it. But the problem was, the content(bytebuf) will be released when it channelRead is fired. Hence i was trying to access the content which was already released. So i made a copy of the content(so it wont be released when channelRead is fired) when i listen for the requests and give to the listener. So he will be able to access the content.


text:
Q: RESTful API using OAuth where authentication tokens are sent as part of the HTTP request I am pretty new to developing APIs. This is part of my class project and the goal is to create a RESTful API in python where the delegation is done via OAuth and these tokens should be sent as part of the HTTP request.
I was advised that I should create an API that involves delegating the OAuth model into a proxy-like approach where authentication tokens are sent as part of the HTTP request. What exactly does a proxy-like approach mean? Any ideas?
I would really appreciate if anyone could help me out with this and also on how to create an API (even if it is not python specific, I can take cue from that)

A: If you are new to REST services, then this link will be nice kick start for you.
You can find here how to develop a basic rest api in python and the same with authentication.
So what is OAuth?
OAuth can be many things. It is most commonly used to allow an application (the consumer) to access data or services that the user (the resource owner) has with another service (the provider), and this is done in a way that prevents the consumer from knowing the login credentials that the user has with the provider.
For example, consider a website or application that asks you for permission to access your Facebook account and post something to your timeline. In this example you are the resource holder (you own your Facebook timeline), the third party application is the consumer and Facebook is the provider. Even if you grant access and the consumer application writes to your timeline, it never sees your Facebook login information.
This usage of OAuth does not apply to a client/server RESTful API. Something like this would only make sense if your RESTful API can be accessed by third party applications (consumers).
In the case of a direct client/server communication there is no need to hide login credentials, the client (curl in the examples above) receives the credentials from the user and uses them to authenticate requests with the server directly.


text:
Q: cross_validation for time series in scikit learn machine learning I wasn't able to find information I am looking for so I will post my question here.
I am just venturing into machine learning. I did my first multiple regression for a time series using scikit learn library.  My code is as shown below
X = df[feature_cols]
y = df[['scheduled_amount']]
index= y.reset_index().drop('scheduled_amount', axis=1)
linreg = LinearRegression()
tscv = TimeSeriesSplit(max_train_size=None, n_splits=11)
li=[]
for train_index, test_index in tscv.split(X):
    train = index.iloc[train_index]
    train_start, train_end = train.iloc[0,0], train.iloc[-1,0]
    test = index.iloc[test_index]
    test_start, test_end = test.iloc[0,0], test.iloc[-1,0]
    X_train, X_test = X[train_start:train_end], X[test_start:test_end]
    y_train, y_test = y[train_start:train_end], y[test_start:test_end]
    linreg.fit(X_train, y_train)
    y_predict = linreg.predict(X_test)
    print('RSS:' + str(linreg.score(X_test, y_test)))
    y_test['predictec_amount'] = y_predict
    y_test.plot()

Not that my data is a time series data and I want to keep the datetime index in my Dataframe when I'm fitting my model.
I am using the TimeSeriesSplit for cross-validation. I still don't really understand the cross validation thing.
First is there a need for a cross-validation in a time series dataset. Second should I use the last linear_coeff_ or should I get the average of all of them to use for my future prediction.

A: Yes there is a need for cross-validation in a timeseries dataset. Basically you need to ensure your model does not overfit your current test and is able to capture past seasonal changes so you can have some confidence in the model doing the same in the future. This method is also used to choose model hyperparameters (i.e. alpha in a Ridge regression).
In order to make future predictions, you should refit your regressor with the whole data and the best hyperparameters or, as @Marcus V. mentioned in the coments, maybe is best to train it only with the most recent data.


text:
Q: How to display images in Rails without plugins like Paper Clip? I'm trying to display images using my web application written in Rails. I've come across solutions like PaperClip, Attachment Fu etc; but they modify my data model and require to save the image through UI. The problem is that, the images content is not stored using Rails, but a Java Servlet Application. Is there a way to just display the blob content of image to my View.
-Snehal

A: class ImagesController < ApplicationController
  caches_page :show
  def show
    if @image = Image.find_by_file_name(params[:file_name])
      send_data(
        @image.file_data,
        :type => @image.content_type,
        :filename => @image.file_name,
        :disposition => 'inline'
      )
    else
      render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
    end
  end
end

map.connect "/images/*file_name", :controller => "images", :action => "show"

Or something like that.


text:
Q: Position the Striped Right Arrow assigned with a macro Let say I have a object: "Striped Right Arrow 2".
I want to create a macro which will position the object "Striped Right Arrow 2". In my macro I have a variable "n".
The following code works (it will position my object to the cell A26, for example with n = 6):
sub mymacro

n=6
ActiveSheet.Shapes.Range(Array("Striped Right Arrow 2")).Top = Range("A" & 2 * n + 10).Top
ActiveSheet.Shapes.Range(Array("Striped Right Arrow 2")).Left = Range("A" & 2 * n + 10).Left

end sub

However, now I want to position my object not only to the first cell (column A), but a column with variable, for example I want to position my object to Cells(2*n+10, n+5), I tried and the following code does not work:
sub mymacro

n=6
ActiveSheet.Shapes.Range(Array("Striped Right Arrow 2")).Top = Cells(2*n+10, n+5).Top
ActiveSheet.Shapes.Range(Array("Striped Right Arrow 2")).Left = Cells(2*n+10, n+5).Left

end sub

Can you correct my code?
Thanks.


text:
Q: Cannot use bigquery udf (bqutil) in processing location: us-west-2 We are trying to use these in us-west2 - https://github.com/GoogleCloudPlatform/bigquery-utils/tree/master/udfs/community.
this first query processes just fine, in US

this second query wont run

Our dataset models is in us West 2. It seems all queries from the 2nd query editor are then processed in us-west 2 where, it seems bqutil does not exist? How can we find the function bqutil.fn.levenshtein when processing in us-west2 (where our datasets all exist)?

A: To use the levenshtein UDF in your BigQuery table, you need to create a UDF in the location where your dataset resides.
You can refer to the below UDF and the screenshot where the data resides in us-west2 location.
UDF :
CREATE OR REPLACE FUNCTION
`stackdemo.fn_LevenshteinDistance`(in_a STRING, in_b STRING) RETURNS INT64 LANGUAGE js AS R"""

var a = in_a.toLowerCase();
var b = in_b.toLowerCase();
 if(a.length == 0) return b.length;
if(b.length == 0) return a.length;
var matrix = [];
// increment along the first column of each row
var i;
for(i = 0; i <= b.length; i++){
 matrix[i] = [i];
}
// increment each column in the first row
var j;
for(j = 0; j <= a.length; j++){
 matrix[0][j] = j;
}
// Fill in the rest of the matrix
for(i = 1; i <= b.length; i++){
 for(j = 1; j <= a.length; j++){
   if(b.charAt(i-1) == a.charAt(j-1)){
     matrix[i][j] = matrix[i-1][j-1];
   } else {
     matrix[i][j] =
       Math.min(matrix[i-1][j-1] + 1, // substitution
       Math.min(matrix[i][j-1] + 1, // insertion
       matrix[i-1][j] + 1)); // deletion
   }
 }
}
return matrix[b.length][a.length];
""";

Query :
SELECT
 source,
 target,
 `stackdemo.fn_LevenshteinDistance`(source, target) distance,
FROM UNNEST([
 STRUCT('analyze' AS source, 'analyse' AS target),
 STRUCT('opossum', 'possum'),
 STRUCT('potatoe', 'potatoe'),
 STRUCT('while', 'whilst'),
 STRUCT('aluminum', 'alumininium'),
 STRUCT('Connecticut', 'CT')
]);

Output :


text:
Q: Please explain the rearrangement of the proof From Valdimir A.Zorich, Mathematical Analysis I, p. 270,
////////////////////////////////////////////////////////////////////////////////////
Proposition 4 If a series $z_1+z_2+\dotsb+z_n+\dotsb$ of complex numbers converges
absolutely, then a series $z_{n_1}+z_{n_2}+\dotsb+z_{n_k}+\dotsb$ obtained by rearranging its terms also converges absolutely and has the same sum.
Proof $\qquad$ Using the convergence of the series $\sum_{n=1}^{\infty}|z_n|$,  given a number $\varepsilon>0$, we choose $N\in\mathbb{N}$ such that $\sum_{n=N+1}^{\infty}|z_n|<\varepsilon$.
We then find an index $K\in\mathbb{N}$ such that all the terms in the sum
$S_N=z_1+\dotsb+z_N$ are among the terms of the sum $\tilde{s}_k=z_{n_1}+\dotsb+z_{n_k}$ for $k>K$. If $s=\sum_{n=1}^{\infty}z_n$, we find that for $k>K$
$$|s-\tilde{s}_k|\leq|s-s_N|+|s_N-\tilde{s}_k|\leq\sum_{n=N+1}^{\infty}|z_n|+\sum_{n=N+1}^{\infty}|z_n|<2\varepsilon$$
Thus we have shown that $\tilde{s}_k\to s$ as $k\to\infty$. If we apply what has just been proved to the series $|z_1|+|z_2|+\dotsb+|z_n|+\dotsb$
and $|z_{n_1}|+|z_{n_2}|+\dotsb+|z_{n_k}|+\dotsb$, we find that the latter series converges. Thus Proposition 4 is now completely proved.
The footnote says:
The term with index $k$ in this series is the term $z_{n_k}$ with index $n_k$ in the original series. Here the mapping $\mathbb{N}\ni k \mapsto nk\in\mathbb{N}$ is assumed to be a bijective mapping on the set $\mathbb{N}$.
//////////////////////////////////////////////////////////////////////////////////////////////////
Please explain the rearrangement of the proof, thanks.


text:
Q: Numbers $n$ such that $n!$ has all of its exponents odd (First paragraph for motivation, second paragraph the actual problem)
I usually have to be on a stand as an embassador for my major (math) for highschoolers, and we usually have problems written on a whiteboard for the kids to try. One of my favorite problems to pose, is whether $50!$ is a square, the idea being that $29$ only appears one time on its prime decomposition (or any prime $26\leq p\leq50$ for that matter). Of course, provided that one knows Bertrand's postulate, this is really easy for arbitrary $n$. But the other day, a kid showed that actually $13$ only appears $3$ times therefore it can't be a prime. So this got me to the following question:
Is there an $n$ relatively big, let's say, greater than $20$ such that all of the exponents of its factorial are odd. In other words, if $n\#$ denotes the product of all the primes less than or equal to $n$, is there an $n$ such that the number
$$\frac{n!}{n\#}$$
is a square?. Since I didn't know what to try I just wrote a very rough python code to check for numbers with that property, and after checking for $n\leq10^5$, the only values are $2,3,4,5$. I didn't want to check more because it took about $20$ minutes to run. I'm very new to programming so I don't doubt the code can be improved, feel free to let me know if you managed to check for bigger $n$. Are these the only ones? And how could I start proving it if so?
Any help is appreciated
My code:
from math import log
from time import time
def s(n,p):
   N=int(log(n,p))
   s=0
   for i in range(1,N+1):
       s=s+int(n/(p**i))
   return s
def P(n):
   prime=[True for i in range(n+1)]
   p=2
   while(p*p<=n):
       if(prime[p]==True):
           for i in range(p*p,n+1,p):
               prime[i]=False
       p=p+1
   l=[]
   for p in range(2,n+1):
       if(prime[p]):
           l.append(p)
   return l
n=int(input("Enter a number greater than or equal to 2: ",))
ti=time()
l=[]
for i in range(2,n+1):
   k=0
   for p in P(i):
       if(s(i,p)%2==1):
           k=k+1
   if(k==len(P(i))):
       l.append(i)
tf=time()
print("There are",len(l),"numbers n from 1 to",n,"such that n! has all of its exponents odd, and these are:")
for i in l:
   print(i)
print("This code took",round(tf-ti,2),"seconds to run")


text:
Q: TYPO3: Where can I find the template created in the backend? I'm trying to create separate templates for webpages with either a single or a double column structure. Currently my webpage only has one template, placed on the root page which is used by all its subpages.
However, I cannot find the template in myextension/Resources/Private/Templates as this folder is empty. Where is the template located in my extension and where should I add the alternative template?

A: I assume you use "fluid_styled_template"? Then the templates are in that respective core directory, in "Resources/Private".
If you want to manipulate them, copy them to your sitePackage into "Resources/Private/Extension/fluid_styled_content" (that at least is one of the recommended ways where to place it) and override the TypoScript that "fluid_stlyed_content" provides.

A: templateis not unique in TYPO3 context. we have:

*

*typoscript records, maybe also as files which are included in a record or by PHP

*HTML files, which are define a markup for parts of the website
they can be differed in

*

*Marker-Templated. The old and less and less used kind with markers and subparts as placeholders for data defined in typoscript

*Fluid templates. The modern kind with control structures and data objects

with the statemant

my webpage only has one template, placed on the root page

it is not clear what you mean:

*

*records are defined in pages -> typoscript templates

*maybe you mean in the root page a template is selected. that could mean HTML templates, probably fluid templates as the path myextension/Resources/Private/Templates matches the usual structure for fluid templates.

assuming fluid templates:
Templates are search in a list of folders. This list is managed in typoscript.
Any usage has it's own list  and the list of your main/page template probably is at page.10.templatePaths. You can look for it in the TSOB (Typoscript Object browser)
If the list consists of one entry only you have only the basic config.
As the list of folders is consulted each time a template (,partial, layout) is accessed and only that file with matching name in the folder with highest priority is taken you can add your folders with higher numbers in the list so you do not need to change the original files (use copies in your folder to modify) or add files to the original folder (inside of other extensions).
So you need two things:

*

*create your template file in an appropriate folder
(ext:myextension/Resources/Private/Templates sounds good)

*and add this folder to the list of folders for these templates
(e.g. page.10.templatePaths.20 = EXT:myextension/Resources/Private/Templates)


text:
Q: Singularities of $\dfrac{z}{\sin\pi z^{2}}$? The function $\dfrac{z}{\sin\pi z^{2}}$ of complex variable $z$. It has a simple pole at $z=0$. There is also 4 poles at $z=\pm\sqrt{n}$  and $z=\pm i\sqrt{n}$ (Where $n\in Z^{+}$). I need to find the order of the pole.please help me on this.

A: All zeros of $\sin$ are of order 1 and located at $\pi\Bbb Z$.
The order of the zero $z=0$ of $\sin z^2$ is 2 because $z^2$ has a zero of order 2 at 0 (and $\sin$ has a simple zero there).
Hence, all poles of $z/\sin z$ are of order 1.


text:
Q: SQL SERVER USER PERMISSION ON LINUX I am planning to install SQL SERVER 2017 on Redhat Linux with least privilege account without using a root account.
What is the linux permission I need for the account to be able to do the setup as well as the folder permission I need on the SQL Server related folders?
Thanks in advance.

A: The installer makes a user and group called mssql that has rw permissions on the related folders.


text:
Q: How can I automatically reboot machine after usb pull off? I have this situation - I've got a boot-able pen-drive with Ubuntu 12.04 for automated installation - when I plug the USB stick in installation begins from it. At the end of installation process I want to put a message on screen to user to pull out the USB stick - because else the installation will be committed again and again after reboot.
So the case is to automatically reboots the machine after the message is shown and pendrive is pulled off from machine.
Any ideas how to achieve this ?


text:
Q: jQuery background-position animation to run more smoothly I have a pattern background animation in jQuery made like this.
        banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');

        window.setInterval(function() {
            banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
            y--;
        }, 150);

Live example http://codepen.io/anon/pen/emMxXa
But it is rather 'jittery'.
How can I make something like this to run more smoothly and slowly.

A: You want to use and look into CSS transitions and CSS animations for real smoothyness.
-webkit-animation: move 30s linear 0s infinite alternate;
-moz-animation: move 30s linear 0s infinite alternate;

@-webkit-keyframes move {
  from { background-position: 0px 0px } to { background-position: 0px 400px }
}

@-moz-keyframes move {
  from { background-position: 0px 0px } to { background-position: 0px 400px }
}

Demo: http://codepen.io/anon/pen/EaEMvy

A: Take a look at this jsFiddle.
You will see that by reducing the interval value from 150 to 30 it will be a lot smoother:
             window.setInterval(function() {
                banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
                y--;
                //x--;

                //if you need to scroll image horizontally -
                // uncomment x and comment y

            }, 30);

You can lower it even more but the more you lower it, the faster it gets also.

A: have a look at https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame
(function($) {

        var x = 0;
        var y = 0;
        //cache a reference to the banner
        var banner = $("#banner");

        // set initial banner background position
        banner.css('backgroundPosition', x + 'px' + ' ' + y + 'px');

        // scroll up background position every 90 milliseconds
        function step() {
            banner.css("backgroundPosition", x + 'px' + ' ' + y + 'px');
            y--;
            //x--;

            //if you need to scroll image horizontally -
            // uncomment x and comment y
                    window.requestAnimationFrame(step)
        }

    window.requestAnimationFrame(step);

})(jQuery);


text:
Q: confusing ltrim charlist behavior Example:
$hello  = "Hello World";
$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);

Which results to:
string(7) "o World"

How come it did not remove d and l at the second word?

A: Because you are using ltrim, which trims left. Only trim trims on both sides.


text:
Q: Substitute all except last block I have this file:
blog.miau.com
api.blog.miau.com
api.nano.miau.uk
willifox.dev.puton.com

And I want this output:
blog-miau.com
api-blog-miau.com
api-nan-.miau.uk
willifox-dev-puton.com

How can I achieve it, I do it with sed, but I substitute all . by -, and I want to leave the last . without replacement. Thanks

A: A sed that should do:
sed 's/\./-/g;s/\(.*\)-/\1\./' file
blog-miau.com
api-blog-miau.com
api-nano-miau.uk
willifox-dev-puton.com

*

*s/#/\./ replace all . with -

*s/\(.*\)-/\1#/ replace last - with .


text:
Q: How to create a heartbeat helper that will then call a error page in Android EDIT:  Added AlarmManager code that is not working
I have a GPS based application that runs on the GPS event every second. Every activity  implements LocationListener and every location listener calls a helper class that does a bunch of stuff (once a second). What I want it for the screen to go red if more than 1 second goes by without a GPS event (say 5 seconds).  Here is some pseudo code:
Here are functions in a helper class
static long heartBeatTimer;

static public void filter(speed){
     //this routine is called once a second unless error
    ....
    heartBeatTimer = System.nanoTime();
    ....
}

static public void heartBeat(){
    //This routine gets called on app launch and runs forever
    While (day != night){
        if (System.nanoTime() - heartBeatTimer > 5000000000) {
            // This is incorrect, I want to go to an ErrorActivity.  Doesn't work
            // Can this be done from a helper class????
            Intent target = new Intent(this, ErrorActivity.class);
            startActivity(target);
        }
    }
}

There are really two questions here.  My heartBeat activity would be all consuming of resources so there must be a better way to do that.  Second, once the heartBeat times out, how can I go to my error activity.
Nothing I try even begins to work.
I have tried using the AlarmManager but this code compiles but crashes with a null pointer exception.
PendingIntent p = setScreenRed();
p.cancel();//or p.cancel();, i am not sure
AlarmManager am=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC, System.currentTimeMillis() + 5000, p);

A: What do you think about this pseudo code:
if(GPS == true){
    doGSPstuff();
    PendingIntent p = setScreenRed();
    alarmManager.cancel(p);//or p.cancel();, i am not sure
    alarmManager.set(5000, p);
}

Basicly it (re)sets the alarmManager every time it get the gps.
If there is no gps it won't reset the alarmManager and it will run after 5 seconds.


text:
Q: Disable Button on CardView android I am having trouble in setting the Button to invisible on a CardView after particular time
What i am trying to achieve:
I have a CardView with a Button.
When user places an order, order date & time is stored in MySQL server DB. I get this time from server and add 10 mins delay to it.
Now this time is considered to make the Button invisble/gone in CardView.
What am i using:
    For time, am using Joda Time &
    whatever code below is inside the onBindViewHolder() of Recyclerview
What i have tried so far:
I get the time from server
String orderDate = cOrder.getOrderDate(); // 2016-08-18 00:02:32

Then convert the time to Date format
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        DateTime dt = dateTimeFormatter.parseDateTime(orderDate);

I add 10 minutes to the time using the below, to set the delay
 DateTime delay = dt.plusMinutes(10);

Now i set the delay time on the Button using postDelayed()
 holder.btnCancel.postDelayed(new Runnable() {
                @Override
                public void run() {
                    holder.btnCancel.setVisibility(View.GONE);
                }
            }, delay.getMillis());

Now when i run the app, the button on the CardView should have disappeared as orderDate was (18th Aug - Two days before current).
I tried using regular Java time as well instead of JODA but no luck.
I am unable to figure out what the issue is. Requesting your guidance.
Thanks

A: @user13 answer is good explain of how postDelayed() works, so you should try this code:
holder.btnCancel.postDelayed(new Runnable() {
            @Override
            public void run() {
                holder.btnCancel.setVisibility(View.GONE);
            }
        }, (10 * 60 * 1000)); // 10 min * 50 sec * 1000 ms
                              // or delay.getMillis() - dt.getMillis()

A: From the documentation of postDelayed():

delayMillis long: The delay (in milliseconds) until the Runnable will
  be executed.

Let's add 10 minutes to 2016-08-18 00:02:32 and convert it to milliseconds (from the epoch). That equals to something like 1471471952000.
You're passing this value to postDelayed() as the delay, effectively telling the Handler to execute this Runnable after 1471471952000 milliseconds, which is roughly equals to 47 years.
That does not really make sense.
To hide your Button if the given Date is before the current Date, you could do something like this:
String orderDateString = cOrder.getOrderDate();
try {
    Date now = new Date();
    Date orderDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
            Locale.getDefault()).parse(orderDateString);

    if(orderDate.before(now)) {
        holder.btnCancel.setVisibility(View.GONE);
    }
} catch (ParseException pe) {
    pe.printStackTrace();
}


text:
Q: `cfg` which is always true / false? For testing purpose I need cfg which is always true / false.
For true I use
#[ cfg( target_pointer_width = "64") ]
...

But obviously it is not general enough.
What is optimal way of expressing cfg to get necessary value?

A: Just do this for a cfg option that is always true:
#[cfg(all())]
fn main() {
    println!("It works!");
}

And if you need a cfg option that is always false you can use:
#[cfg(any())]
fn main() {
    println!("It disappears!");
}


text:
Q: How accurate is the GPS on the iPhone 4? quick question. How accurate is the GPS on the iPhone 4? I ask because I'm working on an enterprise project for a company, and part 2 of it will deal with iDevice development where I have to determine the position of the user. I'd like to know if the GPS is accurate enough to sense the user moving within rooms because the user will have to "tag" sections of the room as they move about it.
Thanks in advance!
P.S. Pressuming that it won't make much of a difference, but the users will actually end up using the iPads, not iPhones, and more than likely the iPad 2 will be out by the time the entire project is completed. I don't know if the iPad 2 will have a better GPS receiver or not, but at the minimum I should use the iPad/iPhone 4 GPS receiver...

A: Most buildings will not allow reception of an accurate set of GPS signals (if they can be received at all) indoors.  The roof/ceiling/floors above are just too thick.  Even a lot of trees overhanging a building will degrade the signal from the GPS satellites.
You might have a chance if all the rooms have very large unobstructed windows with no overhangs, and it's the right time of day for several satellites to be in view out that window.
Outdoors, in the clear, the iPhone 4 GPS seems to be very accurate.  Sometimes I can walk around my parked car, and see the blue dot in the Maps app follow me in a circle.

A: I have done some work with a large location data set. My result set is based on cars driving outside and will therefore be, on average, more accurate than those taken inside (based on line of sight to satellites).
For the 650,704 location updates I used in my tests, I found the average accuracy radius was 246m (91m if your remove >1km outliers). 85.1% of updates had an accuracy of less than 100m. So given that your update will not be as accurate as these, I don't imagine you will have much success tracking indoor location changes.
For a further description of my results.

A: It is very difficult, and most of the time impossible to obtain a GPS signal inside a building. The type of waves used by the GPS (radio waves) are not powerful enough to go through the structure itself.
A simpler and probably cheaper solution would be to give people maybe tags or cards and install some sort of trnasreceiver in each room.

A: It seems the original question was "how accurate is the GPS on an iPhone 4", which hasn't exactly been answered yet.
I've done lots of testing with the accuracy of the GPS chips in iPhone 4, iPhone 4s, and iPhone 5, and the most accurate reading allowed seems to be ~5 meters, or ~16 feet when you're outside with clear line of sight to the sky.  I'm guessing this is a software limitation imposed by Apple to conserve battery.


text:
Q: Как в ListFragment в элементах списка перед текстом поставить изображение? У меня имеется Navigation Drawer Activity. Вот оно, на картинке ниже.

Когда я нажимаю на элемент в списке, меня перекидывает на ListFragment. Он на картинке ниже.

И мне надо на местах, где находятся красные полосочки расположить изображения, при чем в каждом элементе меню нужно чтобы они были разные.
Подскажите как это сделать.
Код ListFragment:
package fragments;

import android.app.ListFragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.ArrayAdapter;

public class Name_ListFragment extends ListFragment
{
String dataname[] = new String[]{"name1", "name2", "name3", "name4", "name5", "name6", "name7"};

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, dataname);

    setListAdapter(adapter);

}
}

A: Самое простое решение:
Во первых, нужно создать разметку айтема, так как андроид не предлагает по умолчанию таких разметок с картинкой. Она будет определять, как будет выглядеть каждый элемент списка. Назовем ее list_item.xml и поместим в папку res/layout/ :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="8dp" />
</LinearLayout>

Здесь важно, что ID виджетов image1 (то, куда будет выводиться картинка) и text1 (то, куда будет выводиться текст) нужно запомнить, они нам пригодятся в дальнейшем.
Сам класс фрагмента:
public class MyListFragment extends ListFragment{

    //Заполняем данные. Имена и соответствующие им картинки в двух массивах
    String dataname[] = new String[]{"name1", "name2", "name3", "name4", "name5", "name6", "name7"};
    int images[] = new int[]{R.drawable.dot, R.drawable.info, R.drawable.command, R.drawable.cube, R.drawable.spider, R.drawable.lock, R.drawable.earth};

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //создаем карту данных для адаптера
        List<HashMap<String,String>> list = new ArrayList<>();

        // Заполняем ее данными
        for(int i=0;i<7;i++){
            HashMap<String, String> hm = new HashMap<>();
            hm.put("keyText", dataname[i]);
            hm.put("keyImage", Integer.toString(images[i]) );
            list.add(hm);
        }

        //Здесь указываем по каким ключам карты получать данные
        String[] from = {"keyImage","keyText"};

        //Здесь указываем ID виджетов на нашей разметке, в которые помещать эти данные
        int[] to = {R.id.image1, R.id.text1};

        //в адаптере указываем разметку айтема, саму карту данных, откуда брать данные и куда помещать
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), list, R.layout.list_item, from, to);
        setListAdapter(adapter);
    }
}


text:
Q: How to search a value which can returns true in WHERE condition OR in HAVING condition? I want to search multi vars that could be true in WHERE condition or in HAVING condition in a group_concat table. Something like this:
SELECT
    article.id,
    article.name,
    GROUP_CONCAT(tags.name order by tags.name) AS nameTags,
    GROUP_CONCAT(tags.id order by tags.id) AS idTags
FROM
    article
    LEFT JOIN ....
    LEFT JOIN ....
WHERE article.name LIKE '%var1%' OR HAVING nameTags LIKE '%var1%' AND
WHERE article.name LIKE '%var2%' OR HAVING nameTags LIKE '%var2%'
GROUP BY id

Is there some way possible or is it better to do 2 querys?
This query:
SELECT
    article.id,
    article.name,
    GROUP_CONCAT(tags.name order by tags.name) AS nameTags,
    GROUP_CONCAT(tags.id order by tags.id) AS idTags
FROM
    article
    LEFT JOIN ....
    LEFT JOIN ....
WHERE
(article.name LIKE '%var1%' OR  tags.name LIKE '%var1%') AND
(article.name LIKE '%var2%' OR  tags.name LIKE '%var2%')
GROUP BY id

Find what I search, but I must do a second query to show results as I want.
sorry if question is repeated, I didn't know how to ask it, so I did'nt know how to search for it. Sorry my english too!

A: SELECT
    article.id,
    article.name,
    GROUP_CONCAT(tags.name order by tags.name) AS nameTags,
    GROUP_CONCAT(tags.id order by tags.id) AS idTags,
    MAX(IF(article.name LIKE '%var1%',1,0)) AS var1match,
    MAX(IF(article.name LIKE '%var2%',1,0)) AS var2match
FROM
    article
    LEFT JOIN ....
    LEFT JOIN ....
GROUP BY id
HAVING
    (nameTags LIKE '%var1%' OR var1match=1)
    OR (nameTags LIKE '%var2%' OR var2match=1)


text:
Q: CSS not referring after hosting in iis I m using vs2010 and iis 7
i hosted my web app in iis 7
like http://localhost/TestUI/login.aspx
But the css file not referring..!
I opened the developer options and tried to see the css file
like http://localhost/TestUI/css/style1.css
It throwing error like

401.3 - unathorized - You do not have permission to view this directory or page because of the access control list (ACL)
  configuration or encryption settings for this resource on the Web
  server.

I have tried many ways to solve it..
Gave access to IUSR to wwwroot folder in properties -> security
Changed Anonymous Authentication to Application pool identity
Used (~) in the css url in aspx page
But don't know how to solve it ! what to do !!

A: As per MSDN

This problem occurs when permissions for the file that the user is trying to access are denied to that user. This error message differs from a standard 401 error message, in that, the user has been logged on to the server, but the resource that the user is trying to access is restricted. For example, if only Administrators and LocalSystem have access to a file on the server and a user, who is a member of the Users group, tries to access it, the user receives a 401.3 (provided they can log on to the server).

The resolution states to check the NTFS permission on that file. Make sure users can access the same.
I found a thread that could help you with the solving the same. As per the thread,

IIS 7 also creates "IUSR" as default user to access files via IIS. So make user IUSR has read access to files/folders.
How to check if IUSR has read Access? Right Click -> Folder -> Properties -> Security Tab See if IUSR is in Group or user names list, If No.
Click Edit -> Add -> Advanced -> Find Now -> Select IUSR and click OK four times


text:
Q: Fastest way to compute for hash of a whole table We need to be able to compute table hashes for an external environment and compare it to pre-computed hash from an internal environment. The use of this is to ensure that data in the external environment is not tampered by a "rogue" database administrator. Users insist this feature.
Currently, we do this by computing the individual hashes of each column value, perform bit-xor on the column hashes to get the row hash, then perform bit-xor on all the row hashes to come up with the table hash. Pseudo-script below:
cursor hash_cur is
select /*+ PARALLEL(4)*/ dbms_crypto.mac(column1_in_raw_type, HMAC_SH512, string_to_raw('COLUMN1_NAME')) as COLUMN1_NAME
       ...
from TABLE_NAME;

open hash_cur;
fetch hash_cur bulk collect into hashes;
close hash_cur;

for i in 1..hashes.count
loop
  rec := hashes(i);
  record_xor = rec.COLUMN1;
  record_xor = bit_xor(record_xor, rec.COLUMN2);
  ...
  record_xor = bit_xor(record_xor, rec.COLUMNN);

  table_xor = bit_xor(table_xor, record_xor);
end loop;

The pseudo-script above will be run in parallel by using dbms_job.
Problem with this is that we have terabytes of data for certain tables and currently the performance does not meet the performance we want to achieve. Hashing must be done "on-the-fly" as users want to perform hash checking themselves.

*

*Do you guys have a better way to perform whole table hashing, or basically comparing tables from different environments which are connected by a low-latency and relatively low-bandwidth network?

It seems to me that the operation is more CPU-bound than I/O bound. I am thinking of storing the table data in a blob instead, where data is properly arranged by record, then by column. Then perform hash on the output file. This should make the operation completely I/O bound.

*What is the fastest way to do this? Anyway to do this within the select clause of a query to remove any overhead PL/SQL-to-SQL engine context switch?

*

*I was thinking of modifiying a global blob for this

*Would also like to remove I/O overhead of bulk collecting the results.

Any suggestions that can lead me to a better performing script would be greatly appreciated. Thanks.

A: First of all, I think the way to approach "rogue administrators" is with a combination of Oracle's audit trail and Database Vault features.
That said, here's what I might try:
1) Create a custom ODCI aggregate function to compute a hash of multiple rows as an aggregate.
2) Create a VIRTUAL NOT NULL column on the table that was an SHA hash of all the columns in the table -- or all the one's you care about protecting.  You'd keep this around all the time -- basically trading away some insert/update/delete performance in exchange to be able to compute hashes more quickly.
3) Create a non-unique index on that virtual column
4) SELECT my_aggregate_hash_function(virtual_hash_column) FROM my_table to get the results.
Here's code:
Create an aggregate function to compute a SHA hash over a bunch of rows
CREATE OR REPLACE TYPE matt_hash_aggregate_impl AS OBJECT
(
  hash_value RAW(32000),
  CONSTRUCTOR FUNCTION matt_hash_aggregate_impl(SELF IN OUT NOCOPY matt_hash_aggregate_impl ) RETURN SELF AS RESULT,
-- Called to initialize a new aggregation context
-- For analytic functions, the aggregation context of the *previous* window is passed in, so we only need to adjust as needed instead
-- of creating the new aggregation context from scratch
  STATIC FUNCTION ODCIAggregateInitialize (sctx IN OUT matt_hash_aggregate_impl) RETURN NUMBER,
-- Called when a new data point is added to an aggregation context
  MEMBER FUNCTION ODCIAggregateIterate (self IN OUT matt_hash_aggregate_impl, value IN raw ) RETURN NUMBER,
-- Called to return the computed aggragate from an aggregation context
  MEMBER FUNCTION ODCIAggregateTerminate (self IN matt_hash_aggregate_impl, returnValue OUT raw, flags IN NUMBER) RETURN NUMBER,
-- Called to merge to two aggregation contexts into one (e.g., merging results of parallel slaves)
  MEMBER FUNCTION ODCIAggregateMerge (self IN OUT matt_hash_aggregate_impl, ctx2 IN matt_hash_aggregate_impl) RETURN NUMBER,
  -- ODCIAggregateDelete
  MEMBER FUNCTION ODCIAggregateDelete(self IN OUT matt_hash_aggregate_impl, value raw) RETURN NUMBER
);

/

CREATE OR REPLACE TYPE BODY matt_hash_aggregate_impl IS

CONSTRUCTOR FUNCTION matt_hash_aggregate_impl(SELF IN OUT NOCOPY matt_hash_aggregate_impl ) RETURN SELF AS RESULT IS
BEGIN
  SELF.hash_value := null;
  RETURN;
END;

STATIC FUNCTION ODCIAggregateInitialize (sctx IN OUT matt_hash_aggregate_impl) RETURN NUMBER IS
BEGIN
  sctx := matt_hash_aggregate_impl ();
  RETURN ODCIConst.Success;
END;

MEMBER FUNCTION ODCIAggregateIterate (self IN OUT matt_hash_aggregate_impl, value IN raw ) RETURN NUMBER IS
BEGIN
  IF self.hash_value IS NULL THEN
    self.hash_value := dbms_crypto.hash(value, dbms_crypto.hash_sh1);
  ELSE
      self.hash_value := dbms_crypto.hash(self.hash_value || value, dbms_crypto.hash_sh1);
  END IF;
  RETURN ODCIConst.Success;
END;

MEMBER FUNCTION ODCIAggregateTerminate (self IN matt_hash_aggregate_impl, returnValue OUT raw, flags IN NUMBER) RETURN NUMBER IS
BEGIN
  returnValue := dbms_crypto.hash(self.hash_value,dbms_crypto.hash_sh1);
  RETURN ODCIConst.Success;
END;

MEMBER FUNCTION ODCIAggregateMerge (self IN OUT matt_hash_aggregate_impl, ctx2 IN matt_hash_aggregate_impl) RETURN NUMBER IS
BEGIN
    self.hash_value := dbms_crypto.hash(self.hash_value || ctx2.hash_value, dbms_crypto.hash_sh1);
  RETURN ODCIConst.Success;
END;

-- ODCIAggregateDelete
MEMBER FUNCTION ODCIAggregateDelete(self IN OUT matt_hash_aggregate_impl, value raw) RETURN NUMBER IS
BEGIN
  raise_application_error(-20001, 'Invalid operation -- hash aggregate function does not support windowing!');
END;

END;
/

CREATE OR REPLACE FUNCTION matt_hash_aggregate ( input raw) RETURN raw
PARALLEL_ENABLE AGGREGATE USING matt_hash_aggregate_impl;
/

Create a test table to work with (you skip this since you have your real table)
create table mattmsi as select * from mtl_system_items where rownum <= 200000;

Create a virtual column hash of each row's data.  Make sure it is NOT NULL
alter table mattmsi add compliance_hash generated always as ( dbms_crypto.hash(to_clob(inventory_item_id || segment1 || last_update_date || created_by || description), 3 /*dbms_crypto.hash_sh1*/) ) VIRTUAL not null ;

Create an index on the virtual column; this way you can compute your hash with an full scan of the narrow index instead of a full scan of the fat table
create index msi_compliance_hash_n1 on mattmsi (compliance_hash);

Put it all together to compute your hash
SELECT matt_hash_aggregate(compliance_hash) from (select compliance_hash from mattmsi order by compliance_hash);

A few comments:

*

*I think it is important to use a hash to compute the aggregate
(rather than merely doing a SUM() over the row-level hashes,
because an attacker could forge the correct sum very easily.

*I don't think you can (easily?) use parallel query because it is
important that the rows be fed to the aggregate function in a
consistent order, or else the hash value will change.

A: you can use ORA_HASH and pass as expression several columns
select sum(ORA_HASH(col1||col2||col3)) as hash from my_table

but here, on AskTom, there's similar discussion about why it's not a good way to do: Creating a unique HASH value for the contents of a table