text:
Q: Solr with large integer lists Is solr able to handle large lists of integers within documents?
Lookups will be exclusively by exact match. Most documents would have ~100  list entries, some would be ~1k and < 10 with up to 25k.
Addition: What is the best schema for large lists?
My idea was an indexed, not stored, multivalued field. The type could be TrieLongField with precisionStep="0". Another idea was to store the data as plain text with a word tokenizer.

A: I would use a multivalued integer field, this should give good performance:
  <fieldType name="int" class="solr.TrieIntField"
      positionIncrementGap="0"
      precisionStep="0"
      omitNorms="true"
      omitTermFreqAndPositions="true"
      multiValued="true" stored="false"
  />


text:
Q: C Linked List - Linking next Linked List Node I have an application which takes multiple command line arguments, amongst the arguments it accepts a file of target hosts which certain actions will be performed against.
173.194.40.225
157.55.152.112
200.49.185.230
195.95.178.226
98.158.27.203

On each line is an IP address of a target, I traverse through the file using the following function;
// Open file read line by line to Linked List
ListNode* file(char *file, char *option)
{

    FILE *ptr_file;
    char buffer[1000];
    char *destination;
    ListNode *linelist;

    // Create an empty line list
    linelist = NULL;

    // Open a file
    if(strcmp(option, "r") == 0)
    {
        ptr_file = fopen(file, option);

        if(!ptr_file)
        {
            printf("Can\'t open file\n\n");
            exit(0);
        }
    }
    else
    {
        printf("File operation not implemented\n\n");
        exit(0);
    }

    // Traverse through the file
    while (fgets(buffer, LINE_MAX, ptr_file) != NULL)
    {
        printf("Line: %s\n", buffer);

        // Add line to Linked List
        linelist = addtoList(linelist, buffer);

        printf("---------------------------------------\n\n");
    }

    printList(linelist);

    // Close the file
    fclose(ptr_file);

    // Return a pointer to linelist
    return linelist;
}

The function is supposed to pass back a pointer to a Linked List of target IP addresses that can be used in a separate socket function. The Linked List has been designed as follows;
// Define node structure
struct listnode
{
    char *data;
    struct listnode *next;
};

// Define node as a type
typedef struct listnode ListNode;

// Add to List
ListNode* addtoList( ListNode *List, char *data );

After the file() function traverses the passed file using a while loop and fgets() to load each line into a buffer, the buffer is passed to a addtoList() function which accepts two variables, a pointer to a Linked List and a pointer to a char which in reality is simply each line of the passed file. The function is meant to add to the end of the passed list.
The function works as follows;
1) Creates a temporary pointer of type ListNode & allocates memory using malloc()
2) Check malloc() doesn't return NULL, if it does then inform user, else fill the temporary ListNode with passed data
3) If the ListNode passed to the function is NULL, simply assign the temporary ListNode to the passed NULL ListNode and return the list
4) If the ListNode passed to the function is not NULL, and the passed ListNode next value is NULL, assign the temporary ListNode to the ListNode next value and return the list
5) If the ListNode passed to the function is not NULL, and the passed ListNode next value is not NULL, create a copy of the pointer to the beginning of the list. Traverse the list using a while loop until we get to the last ListNode which is NULL. Assign the temporary ListNode to the NULL ListNode
The function is as follows;
// Add to List
ListNode* addtoList(ListNode *List, char *data)
{

    printf("Adding: %s\n", data);

    // Create pointer to allocated memory the size of a ListNode
    ListNode* temp = (ListNode*)malloc( sizeof( ListNode ) );

    // Check malloc didn't return NULL
    if(temp == NULL)
    {
        printf( "Can\'t allocate memory for temp, failed to allocate the requested block of memory, a null pointer is returned\n\n" );
        exit(0);
    }
    else
    {
        printf("Memory allocated for temp, filling allocated memory\n\n");

        // Fill the allocated memory where data is a pointer to data
        temp->data = data;
        temp->next = NULL;

        printf("Allocated memory for temp filled with data\n\n");

    }

    printf("temp->data = %s\n\n", temp->data);

    int size = countList(List);
    printf("List size: %i\n\n", size);

    if(List == NULL)
    {
        // If computer can't allocate memory let us know
        printf( "List is empty\n\n" );
        List = temp;
        printf( "List is now temp\n\n" );
        return List;
    }
    else
    if(List != NULL && List->next == NULL)
    {
        printf("List isn\'t empty and List->next is NULL\n\n");

        List->next = temp;
        return List;
    }
    else
    if(List != NULL && List->next != NULL)
    {
        printf("List isn\'t empty and List->next is not NULL\n\n");

        ListNode* Head = List;

        while(Head != NULL)
        {
            printf("List->next data: %s List->next pointer: %p\n\n", Head->data, Head->next);
            Head = Head->next;
        }

        if(Head == NULL)
        {

            printf("Head equals null\n");
            //problem here
            Head->next = temp;

        }

        return List;
    }

}

My problem sits near the very end of the addtoList() function in the if(Head == NULL) conditional statement, the assignment of the temporary ListNode to the Head->next;
if(Head == NULL)
{
    printf("Head equals null\n");
    //problem here
    Head->next = temp;
}

The output of the application is as follows;
######################################

Line: 173.194.40.225

Adding: 173.194.40.225

Memory allocated for temp, filling allocated memory

Allocated memory for temp filled with data

temp->data = 173.194.40.225

List size: 1

List is empty

List is now temp

---------------------------------------

Line: 157.55.152.112

Adding: 157.55.152.112

Memory allocated for temp, filling allocated memory

Allocated memory for temp filled with data

temp->data = 157.55.152.112

List size: 2

List isn't empty and List->next is NULL

---------------------------------------

Line: 200.49.185.230

Adding: 200.49.185.230

Memory allocated for temp, filling allocated memory

Allocated memory for temp filled with data

temp->data = 200.49.185.230

List size: 3

List isn't empty and List->next is not NULL

List->next data: 200.49.185.230
 List->next pointer: 0x8592180

List->next data: 200.49.185.230
 List->next pointer: (nil)

Head equals null
Segmentation fault

The problem I'm having is with the assignment of the temporary ListNode into the NULL ListNode of the listnode structure.
Any help is greatly appreciated...
Edit
So my addtoList() function is now as follows after molbdnilo's &  Diego's recommendations;
// Add to end of List
ListNode* addtoList(ListNode *List, char *data)
{

    char* data_ptr = data;    // Create a pointer to passed data
    char* bkup_copy = NULL;   // Create a null pointer for backing up passed data

    bkup_copy = copyString(data_ptr); // Create a backup of data

    // Create pointer to allocated memory the size of a ListNode
    ListNode* temp = (ListNode*)malloc( sizeof( ListNode ) );

    // Check malloc didn't return NULL
    if(temp == NULL)
    {
        printf("Can\'t allocate memory for temp, failed to allocate the requested block of memory, a null pointer returned\n\n" );
        exit(0);
    }
    else
    {
        // Fill the allocated memory where data is a pointer to data
        temp->data = bkup_copy;
        temp->next = NULL;
    }

    if(List == NULL)
    {
        List = temp;
        return List;
    }
    else
    if(List != NULL && List->next == NULL)
    {
        List->next = temp;
        return List;
    }
    else
    if (List != NULL && List->next != NULL)
    {

        // Create a copy of pointer to passed list
        ListNode* Head = List;

        // Traverse through the list until last item
        while(Head->next != NULL)
        {
            Head = Head->next;
        }

        // Assign temp to the last list item next
        Head->next = temp;

        return List;
    }
    else
    {
        printf("Unknown state of List\n\n");
        exit(0);
    }

}

With a new copyString() function which simply returns a copy of a string as follows;
char* copyString(char* data)
{

    char* data_ptr = data;    // Create a pointer to passed data
    int orig_str_size = 0;    // Create an int to hold passed data size
    char* bkup_copy = NULL;   // Create a null pointer to backup passed data
    int bkup_index = 0;       // Create a index variable for traversal of passed data
    int length;

    // Count the number of characters in data_ptr
    while (*data_ptr++ != '\0')
    {
        orig_str_size++;
    }

    // Dynamically allocate space for a backup copy of data
    bkup_copy = (char*)malloc((orig_str_size+1) * sizeof(char));

    // Check malloc didn't return NULL
    if(bkup_copy == NULL)
    {
        printf("Can\'t allocate memory for bkup_copy, failed to allocate the requested block of memory, a null pointer returned\n\n" );
        exit(0);
    }
    else // Copy data to separate allocated memory
    {
        // Place the '\0' character at the end of the backup string.
        bkup_copy[orig_str_size] = '\0';

        // Assign the pointer to data to the first pointer position in data
        data_ptr = &data[0];

        // The backup string is not the '\0' character copy data to bkup_copy
        while (*data_ptr != '\0'){ bkup_copy[bkup_index++] = *data_ptr++; }
    }

    return bkup_copy;

}

It works as expected now...if anyone can see any problems with that code please let me know so I can fix it now...

A: The problem is that you can't dereference NULL, and you have made very sure that Head is NULL.
You need to stop the traversal earlier, so you can link the new node to the last node in the list.
    // Find the last node - the node with NULL as its 'next'
    while (Head->next != NULL)
    {
        Head = Head->next;
    }
    // 'Head' is now the last node.
    // Replace the NULL at the end of the list with the new node.
    Head->next = temp;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implement Conway's Game of Life in Java The way I have to implement this game is by reading in a file of ones and zeros and then determining the next generation and updating the board accordingly.  This is what I have so far.  I am required to use the five methods given, so I cant change that, I can add some if necessary but I can't get rid of any.  I don't know how I'm supposed to update the existing integer array in the update array by only passing it one 2d integer array.  I tried writing the conditionals in the main method to solve this but I'm completely stuck.  Any advice would be much appreciated.
import java.util.*;
import java.io.*;
public class Proj5{
    public static void main(String[] args)throws FileNotFoundException, NumberFormatException{
    int[][] grid = readBoard("life4.txt");
    System.out.print(boardDisplay(grid));
    System.out.println();
    int rows = grid.length;
    int cols = grid[0].length;
    int[][] temp = new int [rows][cols];

    //Any live cell with fewer than two live neighbors dies of loneliness
    //Any live cell with more than three live neighbors dies of overcrowding
    //Any dead cell with exactly three live neighbors comes to life
    //Any live cell with two or three neighbors stays alive
    //Any dead cell that does not have exactly three live neighbors remains dead
    for(int i = 1; i < rows - 1; i++){
        for (int j = 1; j < cols - 1; j++){
            int friends = neighbors(grid, rows, cols);
            System.out.print(friends);
            if(grid[i][j] == 1 && friends < 2){
                temp[i][j] = 0;
            }
            if(grid[i][j] == 1 && friends > 3){
                temp[i][j] = 0;
            }
            /*else if(grid[i][j] == 0 && friends == 3){
                grid[i][j] = 1;
            }
            else if(grid[i][j] == 1 && (friends == 2 || friends == 3)){
                grid[i][j] = 1;
            }*/
        }
    }
    System.out.print(boardDisplay(temp));

}
//This method should read the specified input file, read it into an int[][] array, and return that array.
public static int[][] readBoard(String filename)throws FileNotFoundException, NumberFormatException{
    Scanner inFile = new Scanner(new File(filename));
    int rows = Integer.parseInt(inFile.nextLine());
    int columns = Integer.parseInt(inFile.nextLine());
    int[][] board = new int [rows + 2][columns + 2];

    for(int i = 1; i < rows - 1; i++){
        String newLine = inFile.nextLine();
        String[] elements = newLine.split("");
        for(int j = 1; j < columns - 1; j++){
            board[i][j] = Integer.parseInt(elements[j]);
        }
    }
    return board;
}
//This method should return the String representing the cells array (so that it would print as a grid if printed).
public static String boardDisplay(int[][] cells){
    String st = "";
    for(int i = 1; i < cells.length - 1; i++){
        for(int j = 1; j < cells[0].length - 1; j++){
            if(cells[i][j] == 0){
                st += ".";
            }
            else{
                st += "*";
            }
        }
        st += "\n";
    }
    return st;
}
//This method should return the number of live neighbors that position (row,col) has in the cells array.
public static int neighbors(int[][] cells, int row, int col){
    int counter = 0;
    for(int i = 1; i < row - 1; i++){
        for(int j = 1; j < col - 1; j++){
            if(cells[i-1][j-1] == 1){
                counter++;
            }
            if(cells[i-1][j] == 1){
                counter++;
            }
            if(cells[i-1][j+1] == 1){
                counter++;
            }
            if(cells[i][j-1] == 1){
                counter++;
            }
            if(cells[i][j+1] == 1){
                counter++;
            }
            if(cells[i+1][j-1] == 1){
                counter++;
            }
            if(cells[i+1][j] == 1){
                counter++;
            }
            if(cells[i+1][j+1] == 1){
                counter++;
            }
            System.out.print(counter);
        }
        System.out.println();
    }
    return counter;
}
//This method should return the next generation of the cells array.
public static int[][] update(int[][] cells){
    for(int i = 1; i < rows - 1; i++){
        for int(j = 1; j < cols - 1; j++){
            if(grid[i][j] == 1 && friends < 2){
                grid[i][j] == update(grid);
            }
        }
    }
}
}

the life4.txt file looks like this:
25
77
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000100000000000000000000000000000000000000000000000000000
00000000000000000000001010000000000000000000000000000000000000000000000000000
00000000000000000000011111000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000010001000000000000000000000000000000000000000000000000000
00000000000000000000110001100000000000000000000000000000000000000000000000000
00000000000000000001010001010000000000000000000000000000000000000000000000000
00000000000000000000110001100000000000000000000000000000000000000000000000000
00000000000000000000010001000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000011111000000000000000000000000000000000000000000000000000
00000000000000000000001010000000000000000000000000000000000000000000000000000
00000000000000000000000100000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000

A: Your update method needs to receive an array, make a temp array, set that temp array's data based on the received array, and return the temp array. So move the code that updates the array out of your main method, and put it into update.
Then, in your main method, read the original grid exactly as you do already, and then call update repeatedly:
int[][] grid = readBoard("life4.txt");
// println original grid
System.out.println(boardDisplay(grid));

for(int i=0; i < 10; i++){ // 10 iterations
    grid = update(grid);
    System.out.println(boardDisplay(grid));
}


text:
Q: Problem proving continuous map theorem for convergence in probability I'm trying to proof the continuous mapping theorem in the context of convergence in probability. I'm following the book "Modern Probability Theory" by B. Ramdas (pages 145-146). Please refer to this link.
At some point he's got the following:

$P[|X_n-X| < \zeta,|X| \leq a] \leq P[|f(X_n)-f(X)| < \eta,|X|\leq a]$

Then it says the following:

But $P[|X_n-X|<\zeta,|X|\leq a]+P[|X_n-X|<\zeta,|X| > a]=\\
> =P[|X_n-X| < \zeta] \geq 1-\epsilon$

I really don't know what am I missing when he concludes that
$1-2\epsilon < P[|X_n-X| < \zeta,|X| \leq a]$
Basically I don't see how he estimates the term $P[|X_n-X|<\zeta,|X| > a]$


text:
Q: Postgresql : Just added a new user, but now says "unknown user"? Still havent understood the basics !!!
The username "postgres" created initially, immediately after installation, allows me to log in. But later I added a new user "p2" with the password "123". When I try to login using the p2 username it doesnt work. I dont know if I am following the right steps, please guide.
revoltman@G41:~$ service postgresql start
revoltman@G41:~$ sudo -u postgres -i
postgres@G41:~$ exit
logout
revoltman@G41:~$ sudo -u p2 -i
sudo: unknown user: p2
sudo: unable to initialize policy plugin

Earlier I had created the new user :
postgres@G41:~$ createuser -P -s -e p2
Enter password for new role:
Enter it again:
CREATE ROLE p2 PASSWORD 'md576be8f31b92b38740013f11b102caa1c'
    SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;
postgres@G41:~$ sudo -u p2 -i
sudo: unknown user: p2
sudo: unable to initialize policy plugin

If I type \du in psql to find list of all users :
                                 List of roles
 Role name |                      Attributes                         | Member of

-----------+------------------------------------------------------------+-
p1         |                                                            | {}
p2         | Superuser, Create role, Create DB                          | {}
postgres   | Superuser, Create role, Create DB, Replication, Bypass RLS | {}

Am I creating new user in a wrong way or my login method is wrong ?
If you want to know any other details please ask.

A: createuser p2 is creating a Postgres user named p2.
sudo is attempting to run a command with the Unix user p2.
These are two completely different things.

A: to connect to posgresql in command line you should use psql psql -U p2 DATABASE_NAME


text:
Q: use aplpy figure in an AxesSubplot instance I have defined a grid of figures in matplotlib using subplots as in this example:
f, axarr = plt.subplots(2)
axarr[0].plot(x, y)

Is it possible to plot a figure generated by aplpy.FITSFigure in one of the axes instances returned by subplots?


text:
Q: How do I tell the remote IP address from within NHttpRequestHandler using Apache httpcomponents? I am implementing a comet-style (delayed response) http server using Apache httpcomponents. My code is very similar to the "Basic non-blocking HTTP server" example at http://hc.apache.org/httpcomponents-core-ga/examples.html
I use a DefaultServerIOEventDispatch and DefaultListeningIOReactor to dispatch requests, just like in the example code. Inside my NHttpRequestHandler I would like to log the IP address of each request.
Inside an HttpRequestHandler you have access to an HttpRequest, an HttpResponse and an HttpContext. With an NHttpRequestHandler you also have an NHttpResponseTrigger. How do I get the remote IP address the request came from? I can't see how to do this with the objects available.
Update, here is the Scala code I ended up using:
def getIp(context: HttpContext): Option[String] = {
  val conn = context.getAttribute(ExecutionContext.HTTP_CONNECTION)

  conn match {
    case inet: HttpInetConnection =>
      inet.getRemoteAddress match {
        case sock: java.net.InetSocketAddress => // HttpComponents 4.1
          Some(sock.getAddress.getHostAddress)
        case adr: java.net.InetAddress => // HttpComponents 4.2
          Some(adr.getHostAddress)
        case unknown =>
          Some(unknown.toString)
      }
    case _ => None
  }
}

As you can see there is an extra step in HttpComponents 4.1.

A: I had a heck of a time figuring this out, so I figured I'll share in case someone wanders across this post in the future.
At first, I was on httpcore-nio 4.1 and getting the connection seemed impossible. Eventually, I did it with a reflections hack (that is probably by no means the best way to do it). After upgrading to 4.2.1 it was considerably easier. I'll share both solutions below. The following code will return 403 Forbidden if the connecting client is not localhost.
HttpCore NIO 4.2
@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) {
    HttpInetConnection connection = (HttpInetConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
    InetAddress ia = connection.getRemoteAddress();
    if("localhost".equals(ia.getHostName()) {
        response.setStatusCode(HttpStatus.SC_FORBIDDEN);
        return;
    }
    ...
}

HttpCore NIO 4.1
A word to the wise: Don't do this. It will work for 4.1, but it will break when upgrading 4.2.x. If you can, upgrade instead.
This solution works for httpcore-nio 4.1 but beware, the code is a horrible, horrible reflections hack to get a private field (iosession) out of a final variable (HttpContext).
@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) {
    try {
        Field f = context.getClass().getDeclaredField("iosession");
        boolean accessible = f.isAccessible();
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        int modifiers = f.getModifiers();
        modifiersField.setAccessible(true);
        modifiersField.set(f, f.getModifiers() & ~Modifier.FINAL & ~Modifier.PRIVATE);
        f.setAccessible(true);
        IOSession io = (IOSession) f.get(context);
        f.setAccessible(accessible);
        modifiersField.set(f, modifiers);
        SocketAddress sa = io.getRemoteAddress();
        if("localhost".equals(((InetSocketAddress) sa).getHostName())) {
            response.setStatusCode(HttpStatus.SC_FORBIDDEN);
            return;
        }
    } catch (Exception e) {
        logger.error("No way! I can't believe this fantastic piece of code threw an exception!", e);
    }
    ...
}

A: One can cast NHttpConnection instance to HttpInetConnection type and call HttpInetConnection#getRemoteAddress method in order to obtain the IP of the opposite endpoint. The connection object can be obtained from the HttpContext instance passed as a parameter to HttpRequestHandler. Alternatively you might want to implement EventListener interface if you want to decouple connection life cycle event logging from your protocol handling logic.
There is also a set of logging classes in the contrib package of HttpCore one can use to extend standard HttpCore classes with wire and I/O event logging capabilities:
http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/httpcore-contrib/src/main/java/org/apache/http/contrib/logging/


text:
Q: MySQL update Trigger to update data table value After Insert on another table I have been stumbling on writing some an MySQL trigger and was hopping someone could help me find the most elegant solution to solve my issue. I have Looked many places and cannot seem to find where the bug is in this code. I also tried not adjusting the delimiter as it seems to create problems I am able to create a trigger without setting the delimiter if I replace the update statement by something else.
The code I have is:
USE MyTable
DELIMITER //

--Trigger to update Scheduling 'Status' and 'Retries' values
CREATE TRIGGER `Scheduling-Updatde_After_Result-Insert`
      AFTER INSERT ON Results
      FOR EACH ROW BEGIN
               UPDATE `Scheduling`
                      SET
                               Running = FALSE,
                               Retries = Retries + 1
                       WHERE ID = NEW.ID;
      END//

DELIMITER ;

I get the following errors:
18:03:25  [DELIMITER - 0 row(s), 0.000 secs]  [Error Code: 1064, SQL State: 42000]  You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER
CREATE TRIGGER acapella.Scheduling-Updatde_After_Result-Insert
 ' at line 1
Code: 1064 SQL State: 42000 --- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER
CREATE TRIGGER Scheduling-Updatde_After_Result-Insert
 ' at line 1
18:03:25  [END - 0 row(s), 0.000 secs]  [Error Code: 1064, SQL State: 42000] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END
DELIMITER' at line 1
Code: 1064 SQL State: 42000 --- You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END
DELIMITER' at line 1


text:
Q: How to add a downloaded .box file to Vagrant? How do I add a downloaded .box file to Vagrant's list of available boxes? The .box file is located on an external drive.
I tried running vagrant box add my-box d:/path/to/box, but Vagrant interprets the path as a URL.

A: First rename the Vagrantfile
then
vagrant box add new-box name-of-the-box.box
vagrant init new-box
vagrant up

Just to check status
vagrant status

that's all

A: F:\PuppetLab\src\boxes>vagrant box add precise32 file:///F:/PuppetLab/src/boxes/precise32.box
==> box: Adding box 'precise32' (v0) for provider:
    box: Downloading: file:///F:/PuppetLab/src/boxes/precise32.box
    box: Progress: 100% (Rate: 1200k/s, Estimated time remaining: --:--:--)
==> box: Successfully added box 'precise32' (v0) for 'virtualbox'!

A: Try to change directory to where the .box is saved
Run vagrant box add my-box downloaded.box, this may work as it avoids absolute path (on Windows?).

A: Solution:
vagrant box add my-box file:///d:/path/to/file.box

Has to be in a URL format.

A: You can point to the folder where vagrant and copy the box file to same location. Then after you may run as follows
vagrant box add my-box name-of-the-box.box
vagrant init my-box
vagrant up

Just to check status
vagrant status

A: Solution for Windows:

*

*Open the cmd or powershell as admin

*CD into the folder containing the .box file

*vagrant box add --name name_of_my_box 'name_of_my_box.box'

*vagrant box list should show the new box in the list

Solution for MAC:

*

*Open terminal

*CD into the folder containing the .box file

*vagrant box add --name name_of_my_box "./name_of_my_box.box"

*vagrant box list should show the new box in the list

A: Alternatively to add downloaded box, a json file with metadata can be created. This way some additional details can be applied. For example to import box and specifying its version create file:
{
  "name": "laravel/homestead",
  "versions": [
    {
      "version": "7.0.0",
      "providers": [
        {
          "name": "virtualbox",
          "url": "file:///path/to/box/virtualbox.box"
        }
      ]
    }
  ]
}

Then run vagrant box add command with parameter:
vagrant box add laravel/homestead /path/to/metadata.json

A: Just to add description for another one case. I've got to install similar Vagrant Ubuntu 18.04 based configurations to multiple Ubuntu machines. Downloaded bionic64 box to one using vagrant up with Vagrantfile where this box was specified, then copied folder .vagrant.d/boxes/ubuntu-VAGRANTSLASH-bionic64 to others.


text:
Q: Duplicate Match Count in MS Excel I am new to MS Excel. I stuck in one problem,
following is the detail description.
I want to find matching rows(cells) from 6 columns and give count in the last column. I have one Key Column and six Haystack columns to search for. If a key found in any of the haystack column then increment last Count column (in front of respective Key Column) by +1 and so on.
For e.g:
Heystack 1   Heystack 2   Heystack 3   Heystack 4   Heystack 5   Heystack 6   Key Column   Count Column
A            D            E            C            F            G            A            2
K            E            A            F            W            Z            E            2
C            Q            R            T            N            B            B            1

Kindly let me know if i can use any formula for Count Column
Thanks in Advance


text:
Q: Weird behaviour when loading view from xib/nib I am experiencing a weird behaviour of my app when loading views from a xib/nib.
I cant access my controls I hooked up with interface builder from code any more-- means I cant replace them or change text and sorts. (the controls will still fire IBActions though.. like button-clicks)
I had this problem already with a uisearchbar. but extensively deleting and adding it again and reconnceting it in Interface Builder somehow solved the issue.
iPad/iPhone uiSearchbar transparent background
I want to avoid doing this with every bloody control in this xib so I tried to nail it down. I found out that as soon as I load a view from my xib, the weird behaviour starts. (though the controls which are already working, as the uisearchbar, keep working)
what I do, is to load a couple of Views(from the same xib the viewcontroller is the owner) to place them into a scrollview. this works nicely..
here is the code:
UIView *viewContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 2304, 575)];
NSArray *nibViews1 = [[NSBundle mainBundle] loadNibNamed:@"ViewController_iPad" owner:self options:nil];
PrescriptionView *view1 = [nibViews1 objectAtIndex:1];
NSArray *nibViews2 = [[NSBundle mainBundle] loadNibNamed:@"ViewController_iPad" owner:self options:nil];
PrescriptionView *view2 = [nibViews2 objectAtIndex:1];
NSArray *nibViews3 = [[NSBundle mainBundle] loadNibNamed:@"ViewController_iPad" owner:self options:nil];
PrescriptionView *view3 = [nibViews3 objectAtIndex:1];
NSMutableArray *arrayViews = [[NSMutableArray alloc] init];
[arrayViews addObject:view1];
[arrayViews addObject:view2];
[arrayViews addObject:view3];
int intX = 1;
int intY = 1;
for (UIView *viewImage in arrayViews)
{
    [viewImage setFrame:CGRectMake(intX, intY, 768, 575)];
    [viewContainer addSubview:viewImage];
    intX = intX + 768;
}

[arrayViews release];
[prescriptionScrollView setContentSize:CGSizeMake(2304, 575)];
[prescriptionScrollView addSubview:viewContainer];
[viewContainer release];

andy ideas? suggestions? is this a bug?
Thank you very much.
Best regards
T

A: As an update for this, I am pretty sure this is a bug.
Placing the view into its own nibfile instead of loading the view from within the same xib helped getting rid of this weird behaviour.
Anyway, I raised a support ticket with apple, but after rejecting my ticket twice for some dumb reasons, I got tired of trying.
thanks to anyone who took the time reading this.
cheers!

A: How are you defining your outlets?  They should be defined like this:
@property (nonatomic, retain) IBOutlet MyView *myViewOutlet;

Also note the outlets should be released and nilled in viewDidUnload and dealloc.


text:
Q: Laravel Excel vertical align center How can I verticaly align center cells with laravel Excel ?
My code :
$sheet->cells('A1:'.$column_end.$i, function ($cells) {
                $cells->setBackground('#d8d8d8');
                $cells->setFontWeight('bold');
                $cells->setValignment('middle');
            });

But it doesn't work, most of my cells are vertically align bottom.
Maybe it's not middle !
I tried 'center' but it didn't work neither. When I tried 'top' or 'bottom' it worked.
So why 'middle' or 'center' didn't ?
Thank for your help.

A: According to Laravel Excel Documentation, it should be:
$cells->setValignment('center');

Like you mentioned...
Try as a test, the setAlignment('center'), according to it, the behavior should be the same but for horizontal. If this one works, then the other one should for sure.

A: Try this
$sheet->cell('A1:G1',function($cell){
$cell->setAlignment('center');
$cell->setFontWeight('bold');
});

A: I had the same problem and I had to dig a bit to understand how it worked and figured it out, so I thought to leave a comment here in case someone else stumble upon the topic
Laravel Excel uses phpspreadsheet and offers a simple Larave interface and logic to work with it, but without much explanation, so, first of all here is the working code (into Exports\MyExportClassExport.php):
/**
     * @return array
     */
    public function registerEvents(): array
    {
        return [
            AfterSheet::class    => function(AfterSheet $event) {
                $event->sheet->getDelegate()->getStyle('A2:W2')->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
            },
        ];
    }

But how does it work and why?
In order to have full control over the spreadsheet and all the really useful components of Phpspreadsheet, Laravel-excel make it possible for you to interact with a series of events, so we are using the AfterSheet event which is triggered after everthing has been created. I am no expert in phpspreadsheet nor in Laravel Excel, so maybe someone can suggest a better event for what I am doing, anyway it works.
We are now hae access to the AfterSheet with a closure with the $event variable and we can access two different properties: sheet and exportable (see AfterSheet class) and we get from the sheet property (which is the Sheet object) the delegate with getDelegate() method and here is the important part. We are now working with the Worksheet class from Phpspreadsheet!
so from now on, we just follow the documentation for Phpspreadsheet and we can work on the code as we wish!
I hope this helped or at least will help someone that, like me, came across this topic without a true answer.


text:
Q: UITableView don't resize correctly with iPad Smart Keyboard I use this code for adapt a textView and a tableView sizes when the virtual keyboard on iPad is shown:
func keyboardWillShown(_ notification: Notification) {
    var info = notification.userInfo!
    let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    UIView.animate(withDuration: 0.5, animations: { () -> Void in

        self.textView_bottomLayoutGuide.constant = keyboardFrame.size.height
        self.tableView_bottomLayoutGuide.constant = keyboardFrame.size.height
    })
}

    func keyboardWillHide(_ notification: Notification) {
    UIView.animate(withDuration: 0.5, animations: { () -> Void in

        self.textView_bottomLayoutGuide.constant = 0
        self.tableView_bottomLayoutGuide.constant = 0
    })
}

All work fine with the virtual keyboard. With the Apple's physical iPad Smart Keyboard, the textView adapt fine (it just keep in count the shortcut and predictive strip) but the tableView behaviour is wrong: it short itself as if a virtual keyboard was shown.


text:
Q: Append URI segment I love the way SO handles URIs. I'd like to mimic the same behaviour in CI. I have a controller called Users and the index method should take one argument, that being the user ID. I search the DB for the username associated with that user ID. Consider that user:1 has username:Santa Claus, how can I append the username to the URI, so that it looks like http://foo.com/users/1/santa-claus
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {

function index($uID = 0) {
    if ($uID > 0) {
        $this->load->model('users_model');
        $uname = $this->users_model->_getUsername($uID);

        #append somehow..

    } else {
        echo('load all users');
    }
}

}

Just to be clear, I'm trying to achieve this:
https://stackoverflow.com/a/11041075/704015

A: application/config/routes.php
$route['users/(:num)/(:any)'] = 'users/index/$1';

Controller
    function index($uID = 0) {
         .....
         $uname = strtolower(str_replace(" ", "-", $uname));

         header("Location: ".base_url()."user/".$uID."/".$uname);

Please include a condition do something else incase username is already present to avoid loop.

A: This in your config/routes.php
 $route['users/(:num)/(:any)'] = 'users/$1/$2';

and this in your controller
public function users($id,$username = FALSE)
{


text:
Q: Python3 cythonize from yocto bitbake recipe problem Let me say this recipe works just fine on our environment with python 2.7, but on new environment where python3 is not. I have no clue why.
Folder/files structure:
zurka-plugin-extensions-EstTV-py3   ---> Folder
    setup.py
    dialog.py
    main.py
    plugin.pyc
    __init__.pyc
    Esttv.png

BB recipe:
DESCRIPTION = "EstTV"
MAINTAINER = "Est"
PV = "4.0"
PR = "r0"

require conf/license/license-gplv2.inc

DEPENDS = "python3 python3-cython python3-cython-native"
RDEPENDS:${PN} = " python3-requests python3-multiprocessing python3-image python3-json ffmpeg "
RRECOMMENDS:${PN} = " python3-pillow nesto-plugin-systemplugins-kauz "

#inherit pkgconfig lib_package setuptools distutils     #py2 - working solution
inherit pkgconfig lib_package setuptools3               #py3??????

SRC_URI = "file://setup.py \
           file://dialog.py \
           file://main.py \
           file://__init__.pyc \
           file://plugin.pyc \
           file://Esttv.png \
"

S = "${WORKDIR}"

do_compile () {
     python setup.py build_ext --inplace
}

do_install () {
    install -d ${D}${libdir}/zurka/python/Plugins/Extensions/EstTV

    install    ${WORKDIR}/*.pyc  ${D}${libdir}/zurka/python/Plugins/Extensions/EstTV/

    install -m 0755 ${S}/dialog.so ${D}${libdir}/zurka/python/Plugins/Extensions/EstTV/
    install -m 0755 ${S}/main.so ${D}${libdir}/zurka/python/Plugins/Extensions/EstTV/

}

Cythonize script (setup.py):
from distutils.core import setup
from Cython.Build import cythonize

def cythonize_modules():
    return cythonize([
        "dialog.py",
        "main.py",
    ],
        language_level=3,  # python3
    )

setup(ext_modules=cythonize_modules())

Error:
ERROR: zurka-plugin-extensions-EstTV-py3-4.0-r0 do_fetch: Fetcher failure:
Unable to find file file://__init__.pyc anywhere.
The paths that were searched were:
    /mnt/h4/7.0/meta-mi/recipes-plugins/zurka-plugin-extensions-EstTV-py3-4.0/mi
    /mnt/h4/7.0/meta-mi/recipes-plugins/zurka-plugin-extensions-EstTV-py3/mi
    /mnt/h4/7.0/meta-mi/recipes-plugins/files/mi
    /mnt/h4/7.0/meta-mi/recipes-plugins/zurka-plugin-extensions-EstTV-py3/
    etc...

As you can see __init__.pyc is inside folder zurka-plugin-extensions-EstTV-py3.
What about inherit, when i put setuptools (without 3) error is different; Could not inherit file classes/setuptools.bbclass.
When i put setuptools3 error is; missing file (__init__.pyc).
When i put distutils, error is different again (i can't remember which one exactly).
So, what i can do next?
Thank you!

EDIT:
after i change do compile line from python setup.py build_ext --inplace to python3 ${S}/setup.py build_ext --inplace now i have another type of error.
Log data follows:
| DEBUG: Executing shell function do_compile
| Traceback (most recent call last):
|   File "/mnt/h4/7.0/builds/ja2/release/sf3000/tmp/work/cortexa15hf-neon-vfpv4-oe-linux-gnueabi/zurka-plugin-extensions-EstTV-py3/5.0-r0/setup.py", line 5, in <module>
|     ext_modules = cythonize("dialog.py")
|   File "/mnt/h4/7.0/builds/ja2/release/sf3000/tmp/work/cortexa15hf-neon-vfpv4-oe-linux-gnueabi/zurka-plugin-extensions-EstTV-py3/5.0-r0/recipe-sysroot-native/usr/lib/python3.9/site-packages/Cython/Build/Dependencies.py", line 965, in cythonize
|     module_list, module_metadata = create_extension_list(
|   File "/mnt/h4/7.0/builds/ja2/release/sf3000/tmp/work/cortexa15hf-neon-vfpv4-oe-linux-gnueabi/zurka-plugin-extensions-EstTV-py3/5.0-r0/recipe-sysroot-native/usr/lib/python3.9/site-packages/Cython/Build/Dependencies.py", line 815, in create_extension_list
|     for file in nonempty(sorted(extended_iglob(filepattern)), "'%s' doesn't match any files" % filepattern):
|   File "/mnt/h4/7.0/builds/ja2/release/sf3000/tmp/work/cortexa15hf-neon-vfpv4-oe-linux-gnueabi/zurka-plugin-extensions-EstTV-py3/5.0-r0/recipe-sysroot-native/usr/lib/python3.9/site-packages/Cython/Build/Dependencies.py", line 114, in nonempty
|     raise ValueError(error_msg)
| ValueError: 'dialog.py' doesn't match any files


text:
Q: Python 3.4 function 'error' output im having problems getting this follow program working as I would like it to. I have one step that is bothering me, I'll quickly go over what works first.  The program takes 2 arguments, pressure and unit, if pressure is an integer and the unit is "pascal","torr","atm" or "mbar" I want it to return "pressure=",pressure,unit. This works. If I dont enter a correct unit, I want the function to print "'unit' is not an accepted unit", this works. Problematic part: When the variable pressure is given a float as 35.2 or a string as "test" BUT I give the variable unit a correct unit such as mbar I get the output  Enter an integer and a unit(seperated by ,): 3045.2,mbar
'3045.2' is not an integer
'mbar' is not an accepted unit
Obviously this is not working like I would want it to, 'mbar' is an accepted unit. Any help would be greatly appreciated. EDIT: Im quite new to programming overall so keep that in mind please :X
 The program I have written:
pressure, unit = input("Enter an integer and a unit(seperated by ,): ").split(',')
def func(pressure, unit):
    try:
        pressure=int(pressure)
    except ValueError:
        print("'"+pressure+"'" + " is not an integer")
    if(isinstance(pressure,int) and (unit == "pascal" or unit == "mbar" or unit == "atm" or unit == "torr")):
        print("pressure =",pressure,unit)
    elif(unit != "pascal" or unit != "mbar" or unit != "atm" or unit != "torr"):
        print("'"+unit+"'" + " is not an accepted unit")
func(pressure, unit)

A: If the unit is mbar but the value is a float then this check will also be False:
if(isinstance(pressure,int) and (unit == "pascal" or unit == "mbar" or unit == "atm" or unit == "torr")):

and that's why you're getting the "is not an accepted unit" message. You need to check for both things entirely separately: is the value an integer (yes/no) and is the unit valid (yes/no). If both are the case then you can print the success message. Otherwise, you'll need to print one or both failure messages independently of each other.

A: You should use else for the except clause - where it will run only if the int(pressure) run correctly. Besides, don't change type of variables; it's confusing:
def func(str_pressure, unit):
    try:
        pressure = int(str_pressure)
    except ValueError:
        print("'{}' is not an integer".format(str_pressure))
    else:
        # `pressure` is assigned
        if unit in {"pascal", "mbar", "atm", "torr"}:
            print("pressure = {} {}".format(pressure, unit))
        else:
            print("'{}' is not an accepted unit".format(unit))

pressure, unit = input("Enter an integer and a unit(seperated by ,): ").split(',')
func(pressure, unit)


text:
Q: Private constructor and android.app.Instrumentation issue In my app, I have implemented a Token class as a singleton to handle user's identification. However, when I launch my app, it fails with the following error:

java.lang.RuntimeException: Unable to instantiate application
  appliflo.Token: java.lang.IllegalAccessException: private
  appliflo.Token() is not accessible from class
  android.app.Instrumentation

I am wondering weather this could be due to the Application class inheritance.
Here is my singleton:
package appliflo;
import android.app.Application;

public final class Token extends Application{

    private static long TokenID;
    private static Token instance;

    private Token(){

    }

    private Token(long TokenID){
        this.TokenID = TokenID;
    }

    public static synchronized Token getToken() {
        if (instance == null) instance = new Token();
        return instance;
    }

    public static synchronized void setToken(long id){
        if (instance == null) instance = new Token(id);
        instance.TokenID = id;
    }

    public long getTokenID(){
        return this.TokenID;
    }

}

A: As your exception message states the class android.app.Instrumentation cannot create an instance of your application because it cannot access its constructor since it is private.
You need to have a public constructor that has no parameters in order to allow the Android system to create an instance of it to start your application.
You will not be creating an instance of Token yourself so the static methods getToken and setToken will not be useful.
Update for question in comment:
If you need to update the tokenId update your get and set methods to only update the long and not create a new instance of your Token class.
public static synchronized long getToken() {
    return TokenID;
}

public static synchronized void setToken(long id){
    TokenID = id;
}


text:
Q: Какие игровые JavaScript фреймворки позволяют подключать файлы ресурсов без обращения к серверу? Подбираю фреймворк для разработки игры на JS. Но возникает одна и та же проблема при разработке: браузер не позволяет коду открывать и вообще работать с файлами локальной ФС.
Скажем, пример с фреймворком Phaser.js ну или Quintus:

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/racemath/data/sprites.json'.

Как же тогда это должно работать на мобильном устройстве без интернета или если я хочу локально отлаживаться и не хочу подымать никакого сервера, предоставляющего файлы джава-скрипту?
А второй вопрос: есть ли какие-то фреймворки, позволяющие таки подключать ресурсы из файлов, или же все это упирается в ту самую проблему запрета доступа к файловой системе ОС из браузера? Тогда я вообще не понимаю, как можно сделать портируемую на мобильные устройства игру, которой в теории не нужен никакой доступ в интернет, она самодостаточна со всеми своими внутренними ресурсами и исполняемым кодом ведь.


text:
Q: Why the encodings from sys.stdout.encoding show those two different results as following? I have two code files which are "run_python.php" and "script.py".
run_python.pyp
<html>
<?php
    $out = `python script.py`;
    $out = iconv('cp949', 'utf-8', $out);
    echo $out;
?>
</html>

script.py
import locale
import sys

print(locale.getdefaultlocale())
print(locale.getpreferredencoding())
print(sys.stdout.encoding)

When I run run_python.php, the output result on the browser is :
('ko_KR', 'cp949') cp949 cp949

When I run the script.py through the cmd("python script.py"), the output result on the cmd is :
('ko_KR', 'cp949')
cp949
utf-8

Why the encodings from sys.stdout.encoding show those two different results?
I'm guessing that they're running on two different shells and the stdout encodings show those two different results?
Is that correct? If that's right or wrong, how do you determine/verify that?
It should be helpful if I could determine which shell I'm using on this testing envorinment which is Windows. I've searched for a long time, but only could I find was only on Linux.
Testing Environment:
System default locale : CP949
Console codepage : CP949
OS : Windows

A: When you run the Python script by itself, sys.stdout is connected to the terminal. When it's connected to a terminal, the default encoding is determined from the LC_CTYPE or LC_ALL environment variables.
When you run it from PHP, sys.stdout is connected to a pipe. In this case, it defaults to 7-bit ASCII.
See Encoding of Python stdout


text:
Q: Should one be concerned about multi-collinearity when using non-linear models? Say we have a binary classification problem with mostly categorical features. We use some non-linear model (e.g. XGBoost or Random Forests) to learn it.

*

*Should one still be concerned about multi-collinearity? Why?

*If the answer to the above is true, how should one fight it considering that one is using these types of non-linear models?

A: Late to the party, but here is my answer anyway, and it is "Yes", one should always be concerned about the collinearity, regardless of the model/method being linear or not, or the main task being prediction or classification.
Assume a number of linearly correlated covariates/features present in the data set and Random Forest as the method. Obviously, random selection per node may pick only (or mostly) collinear features which may/will result in a poor split, and this can happen repeatedly, thus negatively affecting the performance.
Now, the collinear features may be less informative of the outcome than the other (non-collinear) features and as such they should be considered for elimination from the feature set anyway. However, assume that the features are ranked high in the 'feature importance' list produced by RF.
As such they would be kept in the data set unnecessarily increasing the dimensionality. So, in practice, I'd always, as an exploratory step (out of many related) check the pairwise association of the features, including linear correlation.

A: Multi-collinearity will not be a problem for certain models. Such as random forest or decision tree. For example, if we have two identical columns, decision tree / random forest will automatically "drop" one column at each split. And the model will still work well.
In addition, regularization is a way to "fix" Multi-collinearity problem. My answer Regularization methods for logistic regression gives details.

A: *

*Should one still be concerned about multi-collinearity? Why?

If the non-linear model is tree-based model, then you shouldn't consider it serious. Different tree model will have different deal method, such as the random forest will keep them both (because they build the tree independently, and random select the feature for every trees), but it have no effect about the prediction performance, even you remove the redundant one. But for xgboost, it will choose anyone of them, and use it until the last tree build.

*If the answer to the above is true, how should one fight it considering that one is using these types of non-linear models?

It just about the interpretation meaning, so remove the highly correlation variable is suggested.

A: Multi-collinearity is always a possible problem. Variables that are predictors in the model will affect the prediction when they are linearly related (i.e., when collinearity is present).


text:
Q: how to add border to CSS only speech bubble I'm using the following code for pure css speech bubble but however i still can not add border to the whole bubble include the arrow at down side
HTML

Welcome

CSS Code
.bubble {
height: 30px;
width: 574px;
background-color: #9FC175;
background-image: -webkit-linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
background-image: -moz-linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
background-image: -ms-linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
background-image: -o-linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
background-image: linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
border-radius: 5px;
box-shadow: inset 0 1px 1px hsla(0,0%,100%,.5),3px 3px 0 hsla(0,0%,0%,.1);
text-shadow: 0 1px 1px hsla(0,0%,100%,.5);
position: absolute;
}

.bubble:after, .bubble:before {
border-bottom: 25px solid transparent;
border-right: 25px solid #9FC175;
bottom: -25px;
content: '';
position: absolute;
right: 25px;
}

.bubble:before {
border-right: 25px solid hsla(0,0%,0%,.1);
bottom: -28px;
right: 22px;
}

Results

if i added border code border:2px solid #493A34; at class .bubble
Results

Problem
How to add the border to the arrow as well ? ~ any idea
EDIT: Here is the fiddle link with box-shadow applied.

A: You can make a slightly larger brown arrow with the :after psudo-element, and position it behind the smaller green arrow (made with :before), and down 2px to create a border effect.
here's the fiddle: http://jsfiddle.net/rhGCb/
And the css:
.bubble {
  border:2px solid #493A34;
height: 30px;
width: 574px;
background-color: #9FC175;
background-image: -webkit-linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
background-image: -moz-linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
background-image: -ms-linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
background-image: -o-linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
background-image: linear-gradient(top, hsla(0,0%,100%,.5), hsla(0,0%,100%,0));
border-radius: 5px;
box-shadow: inset 0 1px 1px hsla(0,0%,100%,.5),3px 3px 0 hsla(0,0%,0%,.1);
text-shadow: 0 1px 1px hsla(0,0%,100%,.5);
position: absolute;
}

.bubble:before {
border-bottom: 25px solid transparent;
border-right: 25px solid #493A34;
bottom: -27px;
content: '';
position: absolute;
right: 23px;

}

  .bubble:after {
border-bottom: 25px solid transparent;
border-right: 25px solid #9FC175;
bottom: -23px;
content: '';
position: absolute;
right: 25px;
}

A: A bit of a trick, but you can add a box-shadow that behaves as a border (meaning, blur is set to 0):
.speech-bubble{
    /* ... */

    /* 2px = border-width #333 = border-color */
    -webkit-box-shadow:0 0 0 2px #333;
            box-shadow:0 0 0 2px #333;
}


text:
Q: How to add help to winform c# application I want to know that how can I add help support to my winform app.
How do I create chm file for help and how do I integrate it with the application. I want help for almost every control in my application.

A: Take a look at the HelpProvider class.


text:
Q: Hugo theme submodule marked as dirty, doesn't update I'm using the Hugo Whiteplain theme for a personal site hosted through Netlify. I am following tutorial. When I push/publish on GitHub Desktop, I am told that my git submodule is dirty. As a result, I cannot change the theme's background color.
[submodule "themes/whiteplain"]
    path = themes/whiteplain
    url = https://github.com/taikii/whiteplain.git

What do I do to regain control of my theme? Can I change the color without dependence on this dirty submodule?

A: There are many ways to customize a Hugo theme. For instance, you can:

*

*edit the theme directly and let it drift from the original project,

*create a fork and use it as the theme to be able to pull updates
from the original theme while developing your own version,

*edit the theme inside the website itself.

This last option means that you do not touch at the theme itself, but instead make a copy of any file you want to edit inside the tree of your website, following the same path structure, and edit that file.
For any element of any of the customization files (layout, css, scss, etc.) that exists both under the tree of your website and under the tree of the theme, Hugo will prioritize the element in the file under the tree of the website.
For any element not present in the tree of your site, Hugo will use what is in the theme tree instead. This means that you do not have to copy the entire theme or even entire files in your site, but only the elements that you want to customize.
If you choose this method and if you set your theme as a submodule following the Git submodule manual, you will never get into a dirty submodule situation.
Example
Let's say you want to edit the background color of your theme and that the variable is defined in a scss file under:
your_site
  + themes
    + theme_name
      + assets
        + scss
          _content.scss

You need to keep the tree architecture and create a file under:
your_site
  + assets
    + scss
      _content.scss

You can create a file from scratch, but an easier option is to copy the file from the theme and paste it there. In that file, you can customize the background color (or any other setting) however you like.
Note
I have found this way of customizing a theme (which is actually the way advised in the Hugo documentation) to be the simplest.
One situation where this method is not optimal is if you plan to use the same customized version of a theme for several websites. In that case, creating a fork of the original theme makes more sense as you can add your customized theme (your fork) as a submodule of all those websites and your customization is thus portable.


text:
Q: React Using Hook set state undefined when trying delete each item
i using react hooks and got undefined in function 'deletePersonHandler' on 'setPersonsState'.
on the tutorial using 'this.setstate' can delete each item,buat when i trying
all data deleted and didn't return.
when i see the log 'setPersonsState' 'undefined'
solved with this
but still cant set that state,
Person.js

I'm a {props.name} I am {props.age} years old! {props.children}

          <button onClick={props.click}>{props.name} index: {props.indexData}</button>
          <input type="text" onChange={props.changed} value={props.name} />

App.js

// React hooks
const App = () => {
  // state
  // array destructuring
  const [personsState, setPersonsState] = useState({
    persons: [
      { name: 'Max', age: 28 },
      { name: 'Manu', age: 29 },
      { name: 'Stephanie', age: 30 }
    ],
    otherState: [{ phone: '+628762663994' }],
    showPersons: true,
  });

  //Event onClick
  const deletePersonHandler = (personIndex) => {
    const persons = personsState.persons;
    persons.splice(personIndex, 1);
    setPersonsState({ persons: persons });

    console.log(persons);
    console.log(setPersonsState({ persons: persons }));

  };
  // End Event

  //element
  let persons = null;
  if (personsState.showPersons) {
    persons = (

        {personsState.persons.map((person, index) => {
          return <Person
            click={() => deletePersonHandler(index)}
            indexData={index}
            name={person.name}
            age={person.age}
            changed={(setNameChange) => nameChangeHandler(setNameChange)} />
        })}

    );
  }
  //end element

  return (

Hello React

      <button className="button-cus"
        // onClick={() => switchNameHandle('Button')}>Switch Name</button>
        onClick={() => tooglePersonsHandler()}>Toogle Name</button>
      {persons}

  );
}

A: Try this and check live https://vvhoy.csb.app/
  const deletePersonHandler = item => {
    console.log(item);
    let filtered = personsState.persons.filter(
      person => person.age !== item.age
    );
    setPersonsState({ ...personsState, persons: filtered });
  };

pass complete object deletePersonHandler(person)

        {personsState.persons.map((person, index) => {
          return <Person
            click={() => deletePersonHandler(person)}
            indexData={index}
            name={person.name}
            age={person.age}
            changed={(setNameChange) => nameChangeHandler(setNameChange)} />
        })}

Live demo

A: Replace this lane
const persons = personsState.persons;
By
const persons = [...personsState.persons];
you need to include previous state like that setPersonsState({...personsState, persons}) or you delete the showPersons state which cause the if to be false

A: const deletePersonHandler = (personIndex) => {
    //dont use splice because react state must be immutable
    setPersonsState({
        persons: personsState.persons.slice(0, index).concat(personsState.persons.slice(index + 1)),
        otherState: personsState.otherState,
        showPersons: personsState.showPersons
    });
};

I hope it works


text:
Q: How to add extra column actions in jquery jtable I have been working on jquery jtables and having trouble in some conditions. I need to add two column tabs having button which do have their own action during click events. Can I do this with jquery jtable plugin api?

A: Yes you can add extra column in JTable. Here is example given for that.
TestColumn: {
    title: 'Test',
    display: function (data) {
        return '<a href="...">'; //here you can call JavaScript function using  onclick
    }
}


text:
Q: Segmentation fault (core dumped) in qt C++ command line code I am getting a segmentation fault while running a Qt-C++ program:
dlg.h:
#include<QGridLayout>
#include<QPushButton>
#include<QDialog>

class dlg : public QDialog{
        private:
                QPushButton *btn1,*btn2,*btn3,*btn4,*btn5,*btn6,*btn7,*btn8,*btn9,*btn10,*btn11,*btn12;
                QGridLayout *gridlayout;
        public:
                dlg();
};

dlg.cpp:
#include "dlg.h"

dlg::dlg(){
        btn1 = new QPushButton("btn1");
        btn1 = new QPushButton("btn2");
        btn1 = new QPushButton("btn3");
        btn1 = new QPushButton("btn4");
        btn1 = new QPushButton("btn5");
        btn1 = new QPushButton("btn6");
        btn1 = new QPushButton("btn7");
        btn1 = new QPushButton("btn8");
        btn1 = new QPushButton("btn9");
        btn1 = new QPushButton("btn10");
        btn1 = new QPushButton("btn11");
        btn1 = new QPushButton("btn12");

        gridlayout = new QGridLayout(this);

        gridlayout->addWidget(btn1,0,0);
        gridlayout->addWidget(btn2,0,1);
        gridlayout->addWidget(btn3,0,2);
        gridlayout->addWidget(btn4,0,3);
        gridlayout->addWidget(btn5,1,0);
        gridlayout->addWidget(btn6,1,1);
        gridlayout->addWidget(btn7,1,2);
        gridlayout->addWidget(btn8,1,3);
        gridlayout->addWidget(btn9,2,0);
        gridlayout->addWidget(btn10,2,1);
        gridlayout->addWidget(btn11,2,2);
        gridlayout->addWidget(btn12,2,3);

        setLayout(gridlayout);

        setWindowTitle("* QGridLayout  *");
}

main.cpp:
#include<iostream>
#include<QApplication>
#include "dlg.h"
using namespace std;

int main(int argc,char** argv){
        QApplication app(argc,argv);
        dlg obj;
        obj.show();

        return app.exec();
}

I saved this all files in a directory named gridlayout and ran these comamnds in the terminal:
cd /hom/gridlayout/
qmake -project
qmake gridlayout.pro
make

and I am getting this error:

Segmentation fault (core dumped)

Is there any one who can solve this problem. I am referring  Mastering C++ Programming by Jeganathan Swaminathan this book for Qt command line C++ coding.
What is wrong in this code?

A: You repeatedly wrote btn1. You probably meant btn1, btn2, ... Consider using std::list (since GUI elements are probably not copyable) and loops instead of copy-pasting the same line over and over again:
class dlg : public QDialog{
        private:
                std::list<QPushButton> buttons;
                QGridLayout gridlayout;
        public:
                dlg();
};

dlg::dlg() : gridlayout (this) {
    for (std::uint_fast8_t x = 0; x < 3; ++x) {
        for (std::uint_fast8_t y = 0; y < 4; ++y) {
            gridlayout.addWidget (buttons.emplace_back ("btn" + std::to_string(x*4+y)), x, y);
        }
    }

    setLayout(gridlayout);

    setWindowTitle("* QGridLayout  *");
}

This example also avoids the manual memory management.


text:
Q: How to enter array elements into Mysql table? Java I am using the split() function to fill an array and I am trying to enter each element into a Mysql table. What is the best way to do this? How can I make the loop iterate until it reaches the end of the array? I was thinking I might need a scanner object that reads from the array which would allow me to use the .hasNext() function. Is there a better way than this?
String text = "This is my example text string";
String array[] = text.split(" ");

Thanks

A: First of all, text.split(" ") returns String[] not String, but you can loop through the array like this:
String text = "This is my example text string";
String[] array = text.split(" ");
for (String item : array) {
  // do something with each item
  // like build an SQL statement
}


text:
Q: Count distinct values I have a data set asking a customer how many pets they have for example. Is there a way with one query I can count the distinct values (1,2,3, etc)?
Thanks!
+----------+------+
| Customer | Pets |
+----------+------+
|       20 |    2 |
|       21 |    3 |
|       22 |    3 |
|       23 |    2 |
|       24 |    4 |
+----------+------+

What I want is a list saying:

*

*2 had 2 Pets

*2 had 3 Pets

*1 had 4 Pets

A: Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.
I also thought of the SELECT DISTINCT... thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.
So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY clause.
Imagine you have the table customer_pets like this:
+-----------------------+
|  customer  |   pets   |
+------------+----------+
| customer1  |    2     |
| customer2  |    3     |
| customer3  |    2     |
| customer4  |    2     |
| customer5  |    3     |
| customer6  |    4     |
+------------+----------+

then
SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets

would return:
+----------------------------+
|  num_customers  |   pets   |
+-----------------+----------+
|        3        |    2     |
|        2        |    3     |
|        1        |    4     |
+-----------------+----------+

as you need.

A: You can do a distinct count as follows:
SELECT COUNT(DISTINCT column_name) FROM table_name;

EDIT:
Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:

*

*2 customers had 1 pets

*3 customers had 2 pets

*1 customers had 3 pets

Now you're probably going to want to use a subquery:
select COUNT(*) column_name FROM (SELECT DISTINCT column_name);

Let me know if this isn't quite what you're looking for.

A: I think this link is pretty good.
Sample output from that link:
mysql> SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)
    -> FROM book_mast
    -> GROUP BY cate_id;
+---------+---------------------------+-----------------------+
| cate_id | COUNT(DISTINCT(pub_lang)) | ROUND(AVG(no_page),2) |
+---------+---------------------------+-----------------------+
| CA001   |                         2 |                264.33 |
| CA002   |                         1 |                433.33 |
| CA003   |                         2 |                256.67 |
| CA004   |                         3 |                246.67 |
| CA005   |                         3 |                245.75 |
+---------+---------------------------+-----------------------+
5 rows in set (0.00 sec)

A: You can use this:
select count(customer) as count, pets
from table
group by pets

A: SELECT CUSTOMER, COUNT(*) as PETS
FROM table_name
GROUP BY CUSTOMER;


text:
Q: get shipping cost separately for payment gateway in Opencart I'm building a custom payment module which i need to pass the product prices (sub total), tax and the shipping cost separately so the gateway will create and email an invoice for the user.
i managed to find how to get the sub total using $this->cart->getSubTotal()
and the taxes using $this->cart->getTaxes();
but i cant find how to get only the shipping cost
can someone tell me how can i get shipping cost selected for that order separately so i can pass to the payment gateway

A: Well you need to know logic of Open Cart
http://docs.opencart.com/developer-guide
each controller model view language is extend to each object.

find the shipping would be checkout shipping info api/shipping
look at all shipping at the cart hint
                // Shipping Methods
            $json['shipping_methods'] = array();

            $this->load->model('extension/extension');

            $results = $this->model_extension_extension->getExtensions('shipping');

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('shipping/' . $result['code']);

                    $quote = $this->{'model_shipping_' . $result['code']}->getQuote($this->session->data['shipping_address']);

                    if ($quote) {
                        $json['shipping_methods'][$result['code']] = array(
                            'title'      => $quote['title'],
                            'quote'      => $quote['quote'],
                            'sort_order' => $quote['sort_order'],
                            'error'      => $quote['error']
                        );
                    }
                }
            }

this controller of the checkout is the success process of the transaction
catalog/controller/checkout/success.php

here is the last confirmed payments made and clear the session post confirm payment for the next transaction.

A: I believe you were looking for this, For opencart 2.x
$data['totalshippingcost'] =  $this->session->data['shipping_method']['cost'];

Regards


text:
Q: PHP cleanup function unable to remove ' (html_entity_decode not working ?) I am using following cleanup function before inserting it to the db, however i see that
html characters like
'

still remains in the db ? any reason why ? function is
$data = " 'hkh khj  ' ";

echo safe($data);;

function safe($data){
    $data = htmlspecialchars_decode($data);
    $data = html_entity_decode($data);
    //$data = mysql_real_escape_string($data);
    $data = strip_tags($data);
    return $data;
}

A: found the answer
$data = html_entity_decode($data ,ENT_QUOTES, 'UTF-8');


text:
Q: MySQL select non null columns on pivoted table I'm still having some troubles to understand pivoted tables, but I managed to do this working query:
select region,
sum(case when rescheduleCause = 'CLOSED' then round(reschedulePercentage,2) end) as 'CLOSED',
sum(case when rescheduleCause = 'RESHUFFLE' then round(reschedulePercentage,2) end) as 'RESHUFFLE',
sum(case when rescheduleCause = 'NEW PRIORITY' then round(reschedulePercentage,2) end) as 'NEW PRIORITY'

from fancy_table
group by region

I'm getting the following result which calculations are correct:
region  | CLOSED | RESHUFFLE | NEW PRIORITY
___________________________________________
RegionA | 23.08  | NULL      | 38.46
RegiobB | 23.08  | NULL      | 7.69

My problem in that RESHUFFLE column full of NULL values. My desired result set would look like this:
region  | CLOSED | NEW PRIORITY
___________________________________________
RegionA | 23.08  | 38.46
RegiobB | 23.08  | 7.69

I know this can be achieved if I modify this query into a stored procedure using a dynamic sql, but the columns I need are as limitated as these ones, so I think it's not really that necessary. I've tried:
    ifnull(sum(case when rescheduleCause = 'RESHUFFLE' then round(reschedulePercentage,2) end),0) as 'RESHUFFLE',
where `RESHUFFLE` is not null
where 'RESHUFFLE' is not null
having `RESHUFFLE` is not null

I'm out of ideas.

A: When you are querying in SQL you need to know the number of columns ahead of time, you can't just exclude columns on the fly. If you are going to have an unknown number of columns, then you'll need to use dynamic SQL to first create a sql string that will be executed.
In MySQL this can be done using prepared statements.  This will first query your table to only return the rescheduleCause values that you actually have. These values are concatenated together into a sql string, then you'll use this string to create your final query to be executed:
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when rescheduleCause = ''',
      rescheduleCause,
      ''' then round(reschedulePercentage,2) end) AS ',
      replace(rescheduleCause, ' ', '')
    )
  ) INTO @sql
from fancy_table;

SET @sql = CONCAT('SELECT region, ', @sql, '
                    from fancy_table
                    group by region');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See SQL Fiddle with Demo


text:
Q: How use pandas dataframe to convert timestamp? I have a pandas dataframe:

How can I convert them as the "day of the week" and "day of the year" as new columns in the end?

A: Hope this help you.
import pandas as pd

data= {'reservation':
['2015-12-31',
'2015-12-29',
'2015-02-20',
'2015-10-28',
'2015-12-15',
'2015-09-17'
]}

df=pd.DataFrame(data)

df['day_of_week'] = pd.to_datetime(df['reservation']).dt.dayofweek
df['day_name'] = pd.to_datetime(df['reservation']).dt.day_name()
df['day_of_year'] = pd.to_datetime(df['reservation']).dt.dayofyear

print(df)

[Result]:

  reservation  day_of_week   day_name  day_of_year
0  2015-12-31            3   Thursday          365
1  2015-12-29            1    Tuesday          363
2  2015-02-20            4     Friday           51
3  2015-10-28            2  Wednesday          301
4  2015-12-15            1    Tuesday          349
5  2015-09-17            3   Thursday          260


text:
Q: Getting error "System IO.IOException: The directory name is invalid" while installing the App in iOS using Xamarin UI Test I have already developed iOS app and I have not used Xamarin to develop this app. Now I am trying develop UI test cases for my App in iOS Using Xamarin UI test project. I am using Xamarin studio to develop my UI Test Cases in C#.
And I am trying to run the test case project using Mac machine.
Then I am facing error("System IO.IOException: The directory name is invalid") while installing my App using Xamarin test code. Below is the code snippet i am using to install my App in to iOS device.
IApp app = ConfigureApp.iOS .EnableLocalScreenshots() .DeviceIdentifier("f8c67472f88efb1985c2f5e73698d6bb36988f5d").AppBundle("..\app.ipa") .StartApp();

Path for my ipa is correct only.
Can any one please help me on this.

A: AppBundle is the directory containing the .app bundle, not the .ipa. I assume you are using Xcode, so your .app is going to be located in the DerivedData folder unless you mod'ed the build output.
You can also use .InstalledApp({Your app's Bundle ID}) instead, but you will need to install the .ipa on the device before running the tests.
Note: Whether you use the app or spa, just make sure that it is linked against calabash.framework.


text:
Q: "No active account found with the given credentials" in django-rest-framework-simple-jwt I can't optain jwt with django-rest-framework-jwt.
After I post-requested with jwt-optaining-url, it said "No active account found with the given credentials" even though the given information(email, password) is correct.
I think I've created a user with serializer in a wrong way. but can't come up with any new way.
login view
@csrf_exempt
def facebook_login(request):
    body = dict(request.GET)
    code = body['code'][0]

    params_access = {
        "client_id": FACEBOOK_APP_ID,
        "redirect_uri": FACEBOOK_REDIRECT_URI,
        "client_secret": FACEBOOK_SECRET,
        "code": code
    }
    tokens = requests.get("https://graph.facebook.com/v5.0/oauth/access_token", params=params_access).json()
    access_token = tokens['access_token']

    params_debug = {
        "input_token": access_token,
        "access_token": f'{FACEBOOK_APP_ID}|{FACEBOOK_SECRET}'
    }
    debug = requests.get("https://graph.facebook.com/debug_token", params=params_debug).json()

    params_user = {
        "fields": ["email"],
        "access_token": access_token
    }
    user_fb_data = requests.get("https://graph.facebook.com/me", params=params_user).json()
    user_email = user_fb_data['email']

    user = User.objects.filter(email=user_email)
    if not user:
        user_data = {
            'email': user_email,
            'username': user_email,
        }
        user = UserSerializer(data=user_data, partial=True)
        if user.is_valid():
            user.save()
            print("saved!!!!!!!!!!!!!!!")
        else:
            print("error", user.errors)

    jwt_data = {
        'email': user_email,
        'password': access_token
    }
    jwt = requests.post(JWT_OPTAIN_URL, data=jwt_data).json()
    access_token = jwt['access']
    refresh_token = jwt['refresh']
    data = {
        'access_token': access_token,
        'refresh_token': refresh_token
    }
    return Response(data, status=status.HTTP_201_CREATED)

Serializer
class UserSerializer(serializers.ModelSerializer):
    def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(self)
        user.save()
        return user

    class Meta:
        model = User
        fields = ('email', 'username', 'refreshToken', 'password')
        extra_kwargs = {'password': {'write_only': True}}

I expect the jwt is created with email and password information.

A: I finally resolved it with modifying some code and then creating a new user with admin page.
def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user


text:
Q: unit testing vuetify component v-checkbox I wanted to test v-checkbox component.
Calling once trigger click will change the checkbox status checked.
  const flag = wrapper.find('.input-group--selection-controls__ripple')[0]
  flag.trigger('click')

Calling twice trigger click will not change checkbox status unchecked.
How to implement?
  const flag = wrapper.find('.input-group--selection-controls__ripple')[0]
  flag.trigger('click')
  flag.trigger('click')

A: In order to get my test to work I also had to find the specific element below, but I did not need flushPromises().  Finding the right element with the class="input-group--selection-controls__ripple" was the key using the class selector below.  That allowed the click event to update the binding I was trying to test.  Simply finding the
<v-checkbox class-"my-checkbox"/>

was not correct, as the click event didn't work on that element.
it('Does uncheck', async() => {
    // We need to drill down to the .input-group--selection-controls__ripple element so the click works
    const myCheckbox = wrapper.find('.my-checkbox').find('.input-group--selection-controls__ripple');
    myCheckbox.trigger('click');
    expect(wrapper.vm.someField).toEqual(false);
});

A: Try this:
const wrapper = shallowMount(Component)
// If data is loaded asynchronously, use flush-promises to wait for the data to load.
await flushPromises()
 // Find the delete button for the first to-do item and trigger a click event on it.
$emit('.input-group--selection-controls__ripple', event.target.checked)

Check out the Vue Test Utils guide and specifically the async behavior. Additionally, A gentle introduction to testing Vue applications is excellent.

A: Try this:
//in the component
<v-checkbox data-test="select-number"/>

//in the test use this
const selectInput = wrapper.get('[data-test="select-number"]')
expect(selectInput.vnode.elm.checked).toBe(true)


text:
Q: Function in SQL PLUS Can anyone help me to find the error!
SQL>  CREATE OR REPLACE FUNCTION get_pri
   2    (name MENU.ITEM_NAME%TYPE,QUANTITY IN NUMBER) RETURN NUMBER IS
   3    pri MENU.ITEM_PRICE%TYPE ;
   4  BEGIN
   5    SELECT ITEM_PRICE
   6    INTO   pri
   7    FROM   MENU
   8    WHERE  ITEM_NAME = name;
   9    RETURN  (pri*QUANTITY) ;
   10 END get_pri;
   11 /

   Warning: Function created with compilation errors.

A: The function code appears correct.
So, we have to suspect the table and column references. Is there a table MENU in the schema in which you are trying to compile this function? If it is in another schema, you must prefix the table name with the schema name.
Then - does the table MENU have columns ITEM_NAME and ITEM_PRICE?
Of course, I didn't have a table MENU in my schema. After I created one, with two columns, ITEM_NAME and ITEM_PRICE, I was able to compile your function without errors, so it is almost certain this is the issue.


text:
Q: KeyboardAvoidingView should be bottom of view I have a problem with using KeyboardAvoidingView. I have a modal with that shows from bottom of screen. And it has a input then i focus my input Modal goes to center to screen. What i want is that modal should be positioned above of virtual keyboard. Here is a example:
return (
    <AppModalContext.Consumer>
      {(context: ModalContext) => (
        <Modal
          onBackdropPress={() => context.isBackPress() && context.hide()}
          style={context.getStyle()}
          onBackButtonPress={() => context.hide()}
          coverScreen={false}
          isVisible={context.isVisible()}
          swipeDirection={context.getDirection()}>
          <KeyboardAvoidingView
            behavior="padding"
            style={{ backgroundColor: 'lime' }}>
            {context.getContent()}
          </KeyboardAvoidingView>
        </Modal>
      )}
    </AppModalContext.Consumer>
  );

Result is:

What did i do wrong ? any advice ?


text:
Q: VLC: adding media files to playlist via cmd using wildcards I use  VLC 3.0.11 for Windows x64 and want to add media files to a new playlist via cmd using wildcards.
For example:
  "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" ??? "*.ts"

What should I use instead of ??? ?
Thank you

A:
What should I use instead of ??? ?

I am not aware of a native VLC option that would include only files of a certain type. Based on the command line documentation (also available with e.g. vlc -H), the closest option in VLC seems to be --ignore-filetypes which allows the exclusion of certain files by extension ex.:
vlc --ignore-filetypes=jpg,log,m3u,cue "C:\path to files"

Note that as far as I can tell, --ignore-filetypes seems to only be applied when VLC initially starts. Running a second VLC call with --one-instance and --playlist-enqueue but different --ignore-filetypes extension parameters appeared to have no effect during testing in VLC 3.0.11 on Windows (July 2020).

Using A Script
With that said, building off the comment you placed on this answer, you may be able to achieve your goal with a script based around VLC's --one-instance and --playlist-enqueue options and e.g. Windows PowerShell:
ex. vlcq.ps1
# Use basic wildcard notation (ex. "*.mp3") to place
# matching file names from a directory into a VLC
# playlist.

# Set to ex. "C:\path to files\*.mp3" via the command-line
$playlist_path = $args[0]

# Turn ex. "C:\path to files\*.mp3" into ex. "C:\path to files\*"
$playlist_directory = Split-Path -Path $playlist_path
$playlist_directory = $playlist_directory + '\*'

# -Leaf returns the last item or container in a path
# (ex. "*.mp3")
$file_type = Split-Path -Path $playlist_path -Leaf

# Place any matching file names/paths into a $file_list
# $file_list = Get-ChildItem C:\path to files\* -Include *.mp3
$file_list = Get-ChildItem $playlist_directory -Include $file_type

# "Pre-load" VLC for (arguably) better intial playback, etc.
# Start-Process vlc -ArgumentList '--one-instance'
Start-Process "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" -ArgumentList '--one-instance'

foreach ($file in $file_list) {

    # Add quotes to $file output, since this may contain spaces.
    $quoted_file_path = '"' + $file + '"'

    # Queue up the item in the current VLC playlist.
    # Start-Process vlc -ArgumentList '--one-instance', '--playlist-enqueue', $quoted_file_path
    Start-Process "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" -ArgumentList '--one-instance', '--playlist-enqueue', $quoted_file_path

    # Add a delay between loading files to help avoid playlist
    # jumbling. May not be 100% effective.
    Start-Sleep -Seconds 2

    }

Where:

*

*$args[0] is a PowerShell variable containing the first command line value after the script name (ex. a path\wildcard combination like C:\path to files\*.mp3).

*\* is appended to $playlist_directory to ensure the -Include option of Get-ChildItem works correctly (without a final \*, an empty list may be produced).

Note that this script assumes a single playlist play-through. Unfortunately, looping didn't seem to work consistently for me.

Usage
Copy the script above and save it as ex. vlcq.ps1. You can use whatever file name you like but make certain to save it as a .ps1 (PowerShell script) file.
Assuming you opened a command window in the same directory as the saved .ps1 script (above), you could then load files into a VLC playlist with wildcards as follows ex.:
powershell -file .\vlcq.ps1 "C:\path to\*.mp3"

Note that you may need to enable PowerShell script execution before running the command above.
Helper Batch
If the command above is a little long to type, you can wrap it in a batch file e.g.:
ex. vlcq.bat
@ECHO Off

powershell -file "C:\path to\vlcq.ps1" %*

then simply run ex. vlcq "C:\path to\*.mp3" in the same directory as e.g. vlcq.bat. If you want ex. vlcq (a.k.a vlcq.bat) available anywhere from the command line, you can always place it in a folder in your Windows path.
Path Notes

*

*The path to pass to the script for items in the current local directory would be .\ (ex. .\*.mp3).

**.mp3 is just an example. This syntax should work for any media type (i.e. *.ts). Note that this script has a potential side benefit in that it can queue up multiple images from a directory (which doesn't seem normally possible with just ex. vlc "C:\path\to\images").

*If you provide a non-existent extension, etc. (i.e. you use *.mp3 with a directory that contains no .mp3 files), VLC will start (via the first Start-Process command), but no files will be added to the playlist.

*You can use *.* but be aware that this will do exactly what it says. That is, it will load all the files in the directory (including any non-media files).

*You can select items other than by extension with simple Windows regex (e.g. A*.mp3 will select .mp3 files starting with A).

*When passing paths to the script above, some file paths that contain non-standard characters (ex. []) may not load correctly, even if they are generally not an issue in Windows.
Caveats

*

*Remember that the Start-Process commands in the PowerShell script above need a valid path to VLC (assuming VLC isn't available from the command line as just vlc).

*Beware of playlist jumbling. In short, calling VLC for each file (via ForEach and Start-Process) may result in some files being loaded out of order in the current playlist (compared to their order in the directory). Using a delay of e.g. 2 seconds after each call to load a file (via Start-Sleep -Seconds 2) seems to mostly alleviate this, but it may still be possible that some files could be loaded out of order (depending on VLC load times).

*Though initial automatic playback shouldn't be affected, delaying file loading means that loading all the items in a directory may take some time (in the background) compared to e.g. simply opening a directory with ex. vlc "directory name" (which is nearly instantaneous). As a practical side effect, closing VLC before the script has loaded all these files will cause VLC to reopen and begin playing whichever file was last loaded by the script.

*Regarding the powershell command, neither double-quotes around paths nor the -file option to powershell are technically needed if a path does not contain spaces, but paths with spaces will not work correctly without them (you will get a playlist full of essentially invalid items).

*If you add any options to the basic powershell command above, -file should be the final option provided.

PowerShell References

*

*Split-Path

*Get-ChildItem

*ForEach

*Start-Process

*Start-Sleep


text:
Q: Why does beanContainer.getBeanByName(...) return null? I am working through this tutorial:  https://code.google.com/p/jee6-cdi/wiki/DependencyInjectionAnIntroductoryTutorial#Step_2:_Use_the_@Inject_annotation_to_annotate_a_setTransport_se
I get to step 6 where I run into a problem.  It seems
(AutomatedTellerMachine) beanContainer.getBeanByName("atm");

returns null.
I am using JavaSE-1.6.  What could be the cause?
AutomatedTellerMachineImpl:
    package src.main.java;

    import java.math.BigDecimal;

    import javax.inject.Inject;
    import javax.inject.Named;

    @Named("atm")
    public class AutomatedTellerMachineImpl implements AutomatedTellerMachine{

        private ATMTransport transport;

        public void deposit(BigDecimal bd) {
            System.out.println("deposit called");
            transport.communicateWithBank(null);

        }

        public void withdraw(BigDecimal bd) {
            System.out.println("withdraw called");
            transport.communicateWithBank(null);

        }

        @Inject
        public void setTransport(ATMTransport t){
            this.transport = t;
        }

    }

AutomatedTellerMachine:
    package src.main.java;

    import java.math.BigDecimal;

    public interface AutomatedTellerMachine {

        public abstract void deposit(BigDecimal bd);

        public abstract void withdraw(BigDecimal bd);
    }

ATMMain:
    package src.main.java;

    import java.lang.annotation.Annotation;
    import java.math.BigDecimal;

    import org.cdiadvocate.beancontainer.BeanContainer;
    import org.cdiadvocate.beancontainer.BeanContainerManager;

    public class ATMMain {

        public static BeanContainer beanContainer = BeanContainerManager.getInstance();

        static{
            beanContainer.start();
        }

        public static void main (String[] args){

            AutomatedTellerMachine atm = (AutomatedTellerMachine) beanContainer.getBeanByName("atm");

            atm.withdraw(new BigDecimal("10.00"));
            atm.deposit(new BigDecimal("100.00"));
        }
    }

Beans.xml:
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cdi</groupId>
  <artifactId>cdi</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   <description>
        Source code for CDI DI tutorial.
        See: http://code.google.com/p/jee6-cdi/wiki/DependencyInjectionAnIntroductoryTutorial
   </description>

    <dependencies>
        <dependency>
            <groupId>org.cdiadvocate</groupId>
            <artifactId>cdiadvocate-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.cdiadvocate</groupId>
            <artifactId>cdiadvocate-resin-impl</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
<!--                <scope>test</scope> -->
        </dependency>
    </dependencies>

       <repositories>
           <repository>
               <id>cdi.advocate</id>
               <name>CDI Advocacy</name>
               <url>http://jee6-cdi.googlecode.com/svn/m2/repository/</url>
           </repository>
           <repository>
               <id>caucho.maven.repo</id>
               <name>Caucho Repository</name>
               <url>http://caucho.com/m2</url>
           </repository>
       </repositories>
     <build>
       <sourceDirectory>src</sourceDirectory>
       <plugins>
         <plugin>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>3.1</version>
           <configuration>
             <source/>
             <target/>
           </configuration>
         </plugin>
         <plugin>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>2.3.2</version>
           <configuration>
             <source>1.6</source>
             <target>1.6</target>
           </configuration>
           </plugin>
       </plugins>
     </build>
   </project>

A: as HaraldWellmann says - use Weld. It's much easier in this case. For example it works for me:

public static void main(String[] args) {
        Weld weld = new Weld();
        WeldContainer container = weld.initialize();
        AutomatedTellerMachine atm = container
                .instance()
                .select(AutomatedTellerMachine.class)
                .get();

    atm.withdraw(new BigDecimal("10.00"));
    atm.deposit(new BigDecimal("100.00"));
}


text:
Q: Unable to deploy the application i am trying to deploy the application using Tomcat with the help of docker for deployment and mariaDB as database.
The respective generated war file is getting deployed but when i try to access other pages(other than the base url/landing page) its showing the following error:
web-app_1  | 07:20:00.324 [http-apr-8080-exec-3] INFO com.company.controller.MainController - in Main controller
web-app_1  | 07:20:00.806 [http-apr-8080-exec-3] DEBUG org.hibernate.stat.internal.StatisticsInitiator - Statistics initialized [enabled=false]
web-app_1  | 07:20:00.952 [http-apr-8080-exec-3] DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Unable to acquire JDBC Connection [n/a]
web-app_1  | java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=localhost)(port=833)(type=master) : Connection refused (Connection refused)
web-app_1  |    at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.get(ExceptionMapper.java:156)
web-app_1  |    at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.getException(ExceptionMapper.java:118)
web-app_1  |    at org.mariadb.jdbc.internal.util.exceptions.ExceptionMapper.throwException(ExceptionMapper.java:92)
web-app_1  |    at org.mariadb.jdbc.Driver.connect(Driver.java:108)
web-app_1  |    at java.sql.DriverManager.getConnection(DriverManager.java:664)
web-app_1  |    at java.sql.DriverManager.getConnection(DriverManager.java:208)
web-app_1  |    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
web-app_1  |    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
web-app_1  |    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:196)

and hibernate.properties file contains:
jdbc.driverClassName = org.mariadb.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ams_dbnew
jdbc.username = username

jdbc.password = password
hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.hbm2ddl.auto = none
hibernate.format_sql = true
hibernate.show_sql = true

Although am pointing to jdbc:mysql://localhost:3306/ but in tomcat logs its showing error as java.sql.SQLNonTransientConnectionException: Could not connect to address=(host=localhost)(port=833)(type=master) : Connection refused (Connection refused)
and database is running on same 3306 port
sudo netstat -tulpen | grep mysql
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      121        410570      51950/mysqld

can anyone tell me where and which part am doing wrong?
and docker-compose file is:
version: '3'
services:
  web-app:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
       - 8080:8080
    network_mode: "host"

A: I suspect the port 833, try searching the number "833" in your tomcat home directory
cd /TOMCAT_HOME_DIRECTORY/
grep -rli 833 .

may be one of the file overriding the port number.

A: As seeing your logs, it seems there is another database service is configured on 833 port and it is overridden while running tomcat with database app.
Make sure any database you didn't configured with this port. stop all database service then also stop closed this port via following this command:
netstat -ap | grep :
it search the process running on this port
kill -9
kill that process id running on this port no.


text:
Q: How to show difference between two dates and time in php? I have two values:
$c_time = 2016-03-21 14:56:05
$e_time = 2016-03-24 14:56:05

Now I want to show remaining time and days like this:
3 days 0 hour 0 minute 0 second

How I can do this using PHP?

A: You can try this
$c_time = new DateTime('2016-03-21 14:56:05');

$e_time = new DateTime('2016-03-24 14:56:05');

$date_diff = $c_time->diff($e_time);

echo "{$date_diff->days} days {$date_diff->h} hour {$date_diff->i} minute {$date_diff->s} second";

A: - first way:
$datetime1 = strtotime('May 3, 2012 10:38:22 GMT');
$datetime2 = strtotime('06 Apr 2012 07:22:21 GMT');
$secs = $datetime2 - $datetime1;// == return sec in difference
$days = $secs / 86400;

- Another way:
$date1=  new DateTime("May 3, 2012 10:38:22 GMT");
$date2= new DateTime("06 Apr 2012 07:22:21 GMT");
echo $date1->diff($date2)->("%d");

A: $c_time = new DateTime('2016-03-21 14:56:05');
$e_time = new DateTime('2016-03-24 14:56:05');
$interval = $c_time->diff($e_time);
print $interval->format('%a days %h hour %i minutes %s seconds');

print $interval->days; // to obtain the number of days
print $interval->h; // to obtain the number of hours
print $interval->i; // to obtain the number of minutes
print $interval->s; // to obtain the number of seconds

A: You can use date_diff():
$c_time = "2016-03-21 15:56:05";
$e_time = "2016-03-24 15:56:05";
$start = date_create($c_time);
$end = date_create($e_time);
$diff=date_diff($end,$start);
//print_r($diff);
echo $diff->d." days, ".$diff->h." hours, ".$diff->m." minutes, ".$diff->s." seconds";

Result:
3 days, 0 hours, 0 minutes, 0 seconds