text:
Q: Android - How to add file name to an upload file function that calls a PHP file I have the following Java code in my Android app - in a Java class that extends Application:
public static void XSUploadFile(final String filePath, final String fileName, final Activity act, final XSFileHandler handler) {
      new Thread(new Runnable() {
         public void run() {
            upload(filePath, fileName, act, handler);
         }
      }).start();
   }
   public interface XSFileHandler { void done(String fileURL, String error); }
   public static void upload(String sourceFileUri, String fileName, Activity act, final XSFileHandler handler) {
         HttpURLConnection conn;
         DataOutputStream dos;
         String lineEnd = "\r\n";
         String twoHyphens = "--";
         String boundary = "*****";
         final int code;
         int bytesRead, bytesAvailable, bufferSize;
         byte[] buffer;
         int maxBufferSize = 1024*1024;
         File sourceFile = new File(sourceFileUri);
         try {
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(DATABASE_PATH + "upload-file.php");

               conn = (HttpURLConnection) url.openConnection();
               conn.setDoInput(true); // Allow Inputs
               conn.setDoOutput(true); // Allow Outputs

               conn.setUseCaches(false); // Don't use a Cached Copy
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection", "Keep-Alive");
               conn.setRequestProperty("ENCTYPE", "multipart/form-data");
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
               conn.setRequestProperty("file", sourceFileUri);
               dos = new DataOutputStream(conn.getOutputStream());
               dos.writeBytes(twoHyphens + boundary + lineEnd);

               dos.writeBytes("Content-Disposition: form-data; name='file';fileName='" + sourceFileUri + "'" + fileName + "\"" + lineEnd);

               dos.writeBytes(lineEnd);
               bytesAvailable = fileInputStream.available();
               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               buffer = new byte[bufferSize];
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);
               while (bytesRead > 0) {
                  dos.write(buffer, 0, bufferSize);
                  bytesAvailable = fileInputStream.available();
                  bufferSize = Math.min(bytesAvailable, maxBufferSize);
                  bytesRead = fileInputStream.read(buffer, 0, bufferSize);
               }
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
               code = conn.getResponseCode();

               if (code == HttpURLConnection.HTTP_OK) {
                  final HttpURLConnection finalConn = conn;
                  act.runOnUiThread(new Runnable() {
                     public void run() {
                        InputStream responseStream = null;
                        try {
                           responseStream = new BufferedInputStream(finalConn.getInputStream());
                           BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
                           String line;
                           StringBuilder stringBuilder = new StringBuilder();
                           int i = 0;
                           while ((line = responseStreamReader.readLine()) != null) {
                              if (i != 0) { stringBuilder.append("\n"); }
                              stringBuilder.append(line);
                              i++;
                           }
                           responseStreamReader.close();
                           String response = stringBuilder.toString();
                           responseStream.close();
                           finalConn.disconnect();
                           // Log.i(TAG, "XSUploadFile -> " + response);

                           if (response != null) { handler.done(DATABASE_PATH + response, null);
                           } else { handler.done(null, E_401); }

                        // error
                        } catch (IOException e) { e.printStackTrace(); handler.done(null, XS_ERROR); }
                     }});

               // Bad response from sever
               } else {
                  act.runOnUiThread(new Runnable() {
                     public void run() { handler.done(null, XS_ERROR); }});
               }
               fileInputStream.close();
               dos.flush();
               dos.close();

         // No response from server
         } catch (final Exception ex) {
            act.runOnUiThread(new Runnable() {
               public void run() { handler.done(null, XS_ERROR); }});
         }
   }

I call it as it follows:
   // Get demo image path
   Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.demo_img);
   final String filePath = getRealPathFromURI(getImageUri(bmp, ctx), ctx);

    XSUploadFile(filePath, "image.jpg", (Activity)ctx, new XServerSDK.XSFileHandler() {
        @Override
        public void done(String fileURL, String e) {
            if (fileURL != null) {
                hideHUD();
                Log.i("log-", "Uploaded FileURL: " + fileURL);
            }
    }});

And this is my upload-file.php script:
<?php include '_config.php';

if ($_FILES["file"]["error"] > 0) {
    echo "Error: " .$_FILES["file"]["error"]. "<br>";

} else {
    // Check file size
    if ($_FILES["file"]["size"] > 20485760) { // 20 MB
        echo "ERROR: Your file is larger than 20 MB. Please upload a smaller one.";
    } else { uploadImage(); }

}// ./ If

// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
    // generate a unique random string
    $randomStr = generateRandomString();
    $filePath = "uploads/".$randomStr;

    // upload image into the 'uploads' folder
    move_uploaded_file($_FILES['file']['tmp_name'], $filePath);

    // echo the link of the uploaded image
    echo $filePath;
}

// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i<20; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString."_".$_POST['fileName'];
}
?>

The result I get in the Logcat is this one:
Uploaded FileURL: https://xscoder.com/xserver/uploads/mocpWfxIvtRAacnk1lTV_

What I need to do is to append the "image.jpg" to the end of that URL, so the final result should be like:
Uploaded FileURL: https://xscoder.com/xserver/uploads/mocpWfxIvtRAacnk1lTV_image.jpg

I assume it can be done in my XSUploadFile() function in my java class, maybe by editing this line:
dos.writeBytes("Content-Disposition: form-data; name='file';fileName='" + sourceFileUri + "'" + fileName + "\"" + lineEnd);

I've tried a few editing but no success at all.
Note that I cannot edit the PHP script, I have a PHP and iOS SDK that both call that script and work fine, so I must edit only the Android Java code.

A: You need to get the extension from the uploaded file. see the below code.
$filename = $_FILES["file"]["name"];
$file_extension = end((explode(".", $filename)));
$filePath = 'uploads/' . $randomStr.$file_extension;
move_uploaded_file($_FILES["file"]["tmp_name"], $filePath);

EDIT
@xscoder could not edit the php, so I am giving the function in java which return the file extension when you pass filename to that.
private static String getFileExtension(String fileName) {
        if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
        return fileName.substring(fileName.lastIndexOf(".")+1);
        else return "";
}

you can edit this line as
dos.writeBytes("Content-Disposition: form-data; name='file';fileName='" + sourceFileUri + "'" + fileName +"."+ getFileExtension(fileName) +"\"" + lineEnd);

NOTE: while using file in java you need to include this line import java.io.File;

A: I've found a solution by getting inspired from my Swift code, I had to add this code in my upload function:
dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"fileName\"\r\n\r\n" +
                    fileName + "\r\n" +
                    "--" + boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n"

            );

So, the final Java function now looks like this:
 public static void upload(String sourceFileUri, String fileName, Activity act, final XSFileHandler handler) {
         HttpURLConnection conn;
         DataOutputStream dos;
         String lineEnd = "\r\n";
         String twoHyphens = "--";
         String boundary = "*****";
         final int code;
         int bytesRead, bytesAvailable, bufferSize;
         byte[] buffer;
         int maxBufferSize = 1024*1024;
         File sourceFile = new File(sourceFileUri);

         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy);

         try {
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(DATABASE_PATH + "upload-file.php");

               conn = (HttpURLConnection) url.openConnection();
               conn.setDoInput(true);
               conn.setDoOutput(true);
               conn.setUseCaches(false);
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection", "Keep-Alive");
               conn.setRequestProperty("ENCTYPE", "multipart/form-data");
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
               conn.setRequestProperty("file", sourceFileUri);
               dos = new DataOutputStream(conn.getOutputStream());
               dos.writeBytes(twoHyphens + boundary + lineEnd);

            /* HERE'S THE MAGIC CODE :) */
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"fileName\"\r\n\r\n" +
                    fileName + "\r\n" +
                    "--" + boundary + "\r\n" +
                    "Content-Disposition: form-data; name=\"file\"; filename=\"file\"\r\n"

            );

               dos.writeBytes(lineEnd);
               bytesAvailable = fileInputStream.available();
               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               buffer = new byte[bufferSize];
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);
               while (bytesRead > 0) {
                  dos.write(buffer, 0, bufferSize);
                  bytesAvailable = fileInputStream.available();
                  bufferSize = Math.min(bytesAvailable, maxBufferSize);
                  bytesRead = fileInputStream.read(buffer, 0, bufferSize);
               }
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
               code = conn.getResponseCode();

               if (code == HttpURLConnection.HTTP_OK) {
                  final HttpURLConnection finalConn = conn;
                  act.runOnUiThread(new Runnable() {
                     public void run() {
                        InputStream responseStream = null;
                        try {
                           responseStream = new BufferedInputStream(finalConn.getInputStream());
                           BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
                           String line;
                           StringBuilder stringBuilder = new StringBuilder();
                           int i = 0;
                           while ((line = responseStreamReader.readLine()) != null) {
                              if (i != 0) { stringBuilder.append("\n"); }
                              stringBuilder.append(line);
                              i++;
                           }
                           responseStreamReader.close();
                           String response = stringBuilder.toString();
                           responseStream.close();
                           finalConn.disconnect();
                           // Log.i(TAG, "XSUploadFile -> " + response);

                           if (response != null) { handler.done(DATABASE_PATH + response, null);
                           } else { handler.done(null, E_401); }

                        // error
                        } catch (IOException e) { e.printStackTrace(); handler.done(null, XS_ERROR); }
                     }});

               // Bad response from sever
               } else { act.runOnUiThread(new Runnable() {
                     public void run() { handler.done(null, XS_ERROR); }}); }
               fileInputStream.close();
               dos.flush();
               dos.close();

         // No response from server
         } catch (final Exception ex) {
            act.runOnUiThread(new Runnable() {
               public void run() { handler.done(null, XS_ERROR); }});
         }
   }


text:
Q: Socket data race Sockets can generally two way communicate, therefore the same socket can be used to send and recv.
If I wanted to send some data (on another thread) while the socket is getting read, what would the kernel do? This is applied for both parts.
Consider this example: the server is sending you a file and say it will take a lot (low uplink or a very big file). The user gets bored and decides to SIGINT you. You catch it and tell the server to stop sending the file (with some kind of message).
Will you be able to send to tell the server to stop sending even though you're reading from it? And of course, that's applied to the server-side as well.
Hopefully I've been enough clear.

A: Thread 1 can safely write to the socket (with send) whilst thread 2 reads from the socket (with recv). What you need to be careful of is that at the point where you close() the socket the threads are synchronised, else the file descriptor may be used elsewhere, so the other thread (if not synchronized) could read from a file descriptor now used for something else. One way to achieve this would be for your reading thread to shutdown the file descriptor, which should cause the other end to drop the connection and thus error an in-progress send.

A:
If I wanted to send some data (on another thread) while the socket is getting read, what would the kernel do?

Nothing special... sockets aren't like garden hoses... there's just some meta-data added to a packet that's sent between the machines, so the reading and writing happen independently (apart perhaps from if one side calls recv() on a socket that has unsent data in the local buffers due to the Nagle algorithm, which bunches up data into sensible size packets, it might time-out immediately and send whatever it can, but any tuning of that would be an implementation latency-tuning detail and doesn't change the big picture or way the client and server call the TCP API).

Consider this example: the server is sending you a file and say it will take a lot (low uplink or a very big file). The user gets bored and decides to SIGINT you. You catch it and tell the server to stop sending the file (with some kind of message).  Will you be able to send to tell the server to stop sending even though you're reading from it? And of course, that's applied to the server-side as well.

The kernel accepts a limited amount of data to be sent, and a limited amount of data received, after which it forces the sending side to wait until some has been consumed before sending more.  So, if you've sent data to a server, then get a local SIGINT and send a "oh, cancel that" in the same way, the server must read all the already-sent data before it can see the "oh, cancel that".  If instead of sending it "in the same way" you turn on the Out Of Band (OOB) flag while sending the cancel message, then the server can (if it's written to do so) detect that there's OOB data and read it before it's completed reading/processing the other data.  It will still need to read and discard whatever in-band data you've already sent, but the flow control / buffering mentioned above means that should be a manageable amount - far less than your file size might be.  Throughout all this, whatever you want to recv or the server sends is independent and unaffected by the large client->server send, any OOB data etc..
There's a discussion and example code from GNU at http://www.gnu.org/software/libc/manual/html_node/Out_002dof_002dBand-Data.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: TCP to virtual serial port with socat I have a program (program 1) that has a TCP server listening on port 1234. I have confirmed that the server accepts connections and sends data with a utility str2str.
Program 2, on the same machine, needs this data but is configured to receive it via a serial port. I need to somehow forward the TCP data to (I believe) a virtual serial port.
I tried setting up the following virtual serial port pair, with the idea of streaming the TCP data to /dev/ttyVA00 so that program 2 can read the data from the paired ttyVB00:
sudo socat -d -d PTY,raw,echo=0,link=/dev/ttyVA00 PTY,raw,echo=0,link=/dev/ttyVB00

The link is set up however I'm really lost here, I tried the following but I can see no data coming in at ttyVB00:
sudo socat TCP:localhost:1234 pty,link=/dev/ttyVA00,raw,echo=0

Can someone please put me on the right track? Or better still, provide a solution?
Thanks

A: Your second command doesn't open the existing /dev/ttyVA00 device; you're asking socat to create a new pty device at that location, overwriting the old one. (In TCP terms, it's not connecting to /dev/ttyVA00 – it's listening for incoming connections at /dev/ttyVA00.)
However, your second command on its own would already be enough to stream the TCP data to whatever process opens the /dev/ttyVA00 device. There is no need to create a pair of ptys, as the entire point of a pty is that software could directly attach to the "back end" of one. (Indeed that's what socat would do in the first command! It doesn't create a linked pair of ptys A–B; it's just A–socat and socat–B.)

A: Thanks @user1686, you helped me solve it, as you noted my second command was overwriting the device rather than writing to it. A virtual pair was however necessary:
sudo socat -d -d pty,link=/dev/ttyVA00,echo=0,perm=0777 pty,link=/dev/ttyVB00,echo=0,perm=0777

The second command connects to Program 1 and forwards its data stream to ttyVA00 specifying the baud rate:
socat TCP:localhost:1234 /dev/ttyVA00,b115200,raw,echo=0

Now ttyVB00 is accessible with minicom, for example:
minicom -b 115200 -o -D /dev/ttyVB00


text:
Q: C++-17: cast function pointer to function with different argument pointer type I have a legacy C-API which provides callbacks for asyncrounous operations.
Since this library requires many compiler flags, is full of macros and the header generates tons of warnings when included, I decided to create a wrapper for this library that encapsulates the proprietary C-library.
But since this library is asyncronous, it provides callback functions.
The problem is, that the callback requires a pointer to a struct (X_leg).
But since this struct is part of the old API and I don't want to include the struct,
I decided to create a struct with the same layout X_wrp.
In the main() I ensure that the size of both structs is equal.
My question is now:
Is it safe to reinterpret_cast the wrapper function pointer of type func_wrp to the legacy function pointer with type func_leg?
Or is it undefined behavior in C++17?
I have the following minimal working example:
#include <iostream>
#include <cstdint>

//begin of wrapper decls
struct X_wrp {
    std::uint32_t member;
};

using func_wrp = void (*)(const X_wrp* arg);

void caller_wrp(func_wrp func);
//end of wrapper decls

//Legacy C-Code
typedef struct {
    std::uint32_t member;
} X_leg;

typedef void (*func_leg)(const X_leg* arg);

void caller_leg(func_leg func) {
    static X_leg inst{10};
    func(&inst);
}
//End of Legacy C-Code

void callback(const X_wrp* arg) {
    std::cout << arg->member << std::endl;
}

int main() {
    static_assert(sizeof(X_leg)==sizeof(X_wrp));//ensures that there is no oops
    caller_wrp(callback);
    return EXIT_SUCCESS;
}

//begin of wrapper implementations
void caller_wrp(func_wrp func) {
    caller_leg(reinterpret_cast<func_leg>(func)); //is this cast safe?

}
//end of wrapper implementations

A: No, this is not safe and is explicitly called out as undefined behavior in [expr.call]/6

Calling a function through an expression whose function type is different from the function type of the called function's definition results in undefined behavior.

This is also reinforced in the reinterpret_cast documentation about function pointer conversions  [expr.reinterpret.cast]/6

A function pointer can be explicitly converted to a function pointer of a different type. [ Note: The effect of calling a function through a pointer to a function type ([dcl.fct]) that is not the same as the type used in the definition of the function is undefined ([expr.call]). — end note ] Except that converting a prvalue of type "pointer to T1" to the type "pointer to T2" (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified. [ Note: See also [conv.ptr] for more details of pointer conversions. — end note ]


text:
Q: Sort xls file content by mutiple column with data-type I have to sort xls file content by 4 columns in ascending order.
I converted xls file content into list of list. Following is input
Input:
data = """ABC, Do not Consider1, 101, Title and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 99, BIC Codes, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 98, Title and Subtitle, Do not Consider2, 25/12/2015
ABC, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 30/12/2015"""

Respective output in string format:
 data = """ABC, Do not Consider1, 98, Title and Subtitle, Do not Consider2, 25/12/2015
ABC, Do not Consider1, 99, BIC Codes, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 101, Title and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
"""

First I Split data to list format:
    # Split data to list.
>>> data_list = [i.split(", ") for i in  data.split("\n")]

>>> print "\n".join([", ".join(i) for i in  data_list])
ABC, Do not Consider1, 101, Title and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 99, BIC Codes, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 98, Title and Subtitle, Do not Consider2, 25/12/2015
ABC, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 30/12/2015

Following is sorting requirement:
- We have to sort by index0 ,
   if index0 have same values for multiple items then sort by Index2
       if index0 and index2 are same for multiple items then sort by Index3
           if index0, index2 and index3 are same for multiple items then sort by Index5

My Logic was

*

*to create string of index0, index2, index5 and index5

*Create dictionary with key from the step 1

*Use sorted function to sort key list

*Again create xls file.

code:
>>> from collections import defaultdict
>>> data_dict = defaultdict(list)
>>> for i in data_list:
...     key = "%s%s%s%s"%(i[0].strip(), i[2].strip(), i[3].strip(), i[5].strip())
...     data_dict[key].append(i)
...
>>> sorted_keys = sorted(data_dict.keys())
>>>
>>> for i in sorted_keys:
...     for j in data_dict[i]:
...         print j
...
...
['ABC', 'Do not Consider1', '100', 'ATitle and Subtitle', 'Do not Consider2', '30/12/2015']
['ABC', 'Do not Consider1', '100', 'Title and Subtitle', 'Do not Consider2', '30/12/2015']
['ABC', 'Do not Consider1', '100', 'Title and Subtitle', 'Do not Consider2', '31/12/2015']
['ABC', 'Do not Consider1', '101', 'Title and Subtitle', 'Do not Consider2', '30/12/2015']
['ABC', 'Do not Consider1', '98', 'Title and Subtitle', 'Do not Consider2', '25/12/2015 ']
['ABC', 'Do not Consider1', '99', 'BIC Codes', 'Do not Consider2', '31/12/2015']
['XYZ', 'Do not Consider1', '100', 'ATitle and Subtitle', 'Do not Consider2', '30/12/2015']
['XYZ', 'Do not Consider1', '100', 'ATitle and Subtitle', 'Do not Consider2', '30/12/2015']

But there are Numbers in Index2 i.e. column two and Date in Index5 i.e. column5, so not get sorted data.
Can you help me to fix this?

A: You can sort by multiple keys using the sorted function as follows:-
sorted_list = sorted(data_list, key=lambda item: (item[0], int(item[2]), item[3]))
print "\n".join([", ".join(i) for i in  sorted_list])

returns
ABC, Do not Consider1, 98, Title and Subtitle, Do not Consider2, 25/12/2015
ABC, Do not Consider1, 99, BIC Codes, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 101, Title and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015

The trick is to let your key lambda return a tuple containing all the values to sort on, and to convert the third column's values to integers by using the int() function.

A: You should be able to do what you need with a single sorted() call. The csv module can be used to parse the data:
import csv
import StringIO
from itertools import groupby

data = """ABC, Do not Consider1, 101, Title and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 99, BIC Codes, Do not Consider2, 31/12/2015
ABC, Do not Consider1, 98, Title and Subtitle, Do not Consider2, 25/12/2015
ABC, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
XYZ, Do not Consider1, 100, ATitle and Subtitle, Do not Consider2, 30/12/2015
ABC, Do not Consider1, 100, Title and Subtitle, Do not Consider2, 30/12/2015"""

csv_input = csv.reader(StringIO.StringIO(data), skipinitialspace=True)
rows = sorted(list(csv_input), key=lambda x: (x[0], int(x[2]), x[3], x[5]))

for row in rows:
    print row

This would give you the following:
['ABC', 'Do not Consider1', '98', 'Title and Subtitle', 'Do not Consider2', '25/12/2015 ']
['ABC', 'Do not Consider1', '99', 'BIC Codes', 'Do not Consider2', '31/12/2015']
['ABC', 'Do not Consider1', '100', 'ATitle and Subtitle', 'Do not Consider2', '30/12/2015']
['ABC', 'Do not Consider1', '100', 'Title and Subtitle', 'Do not Consider2', '30/12/2015']
['ABC', 'Do not Consider1', '100', 'Title and Subtitle', 'Do not Consider2', '31/12/2015']
['ABC', 'Do not Consider1', '101', 'Title and Subtitle', 'Do not Consider2', '30/12/2015']
['XYZ', 'Do not Consider1', '100', 'ATitle and Subtitle', 'Do not Consider2', '30/12/2015']
['XYZ', 'Do not Consider1', '100', 'ATitle and Subtitle', 'Do not Consider2', '30/12/2015']


text:
Q: Bluetooth device still paired after clean install I'm facing some issue with Bluetooth device(s) still paired to my Mac after a clean install.
I'm currently using a 2013 Macbook Pro on Sierra, which was previously used by one of my co-worker for the last year. He switched to another computer and after doing a clean install (internet recovery) he then gave it to me. (Mavericks was installed then I installed Sierra).
So, here it is: he has an iPhone which he had previously paired to the Macbook, along with a magic mouse which he gave to me.
To my big surprise, the other day I saw that in the bluetooth icon has changed, and that his iPhone and the mouse (which I had not used yet) was already paired to the Macbook (mark as connected) without asking anything !
I was even able to browse the files on his own phone...
I'm starting to think I'm facing some serious security issue, or we missed something in the clean install procedure but I did not see anything like that on any site nor anyone talking about this ( except maybe this unsolved old thread explaining a similar problem but the devices were not connected for this one...)
I just want to say that I already tried to:

*

*delete the device from the bluetooth menu (holding Option key > [device name] > Delete but then it connected itself automatically some minutes later)

*Shift + Option bluetooth menu > Debug > Reset bluetooth module (same result)

*Cmd + Shift + P + R to reset NVRAM at boot (this seemed to work for several days, but then it connected automatically again today, still without asking anything!)

Does this sound familiar to anyone?

A: Just to clarify, have you tried either of the following:

*

*On the MacBook Pro go to System Preferences > Bluetooth and right-click on the device (his iPhone) and select Remove

*On his iPhone, go to Settings > Bluetooth and tap on the 'info' icon on the right of your MacBook Pro  and then tap the Forget This Device option

Doing this should solve your issue. For good measure, I would do both.
If the above steps don't work, try resetting the iPhone settings. Your co-worker can do this on his iPhone by going to Settings > General > Reset > Reset All Settings. However, make sure he has his passcode and Wi-Fi passwords handy.
Finally, if you happen to not be using any Bluetooth devices with the MacBook, you can also turn it off totally from System Preferences > Bluetooth.


text:
Q: How to solve this second order differential equation? The equation is given by:
$$ \frac{dv}{du}\left(2 u\frac{1-uv}{1+uv} + u\right) = \frac{v}{2} \frac{d^2v}{du^2} + v\frac{1-uv}{1+uv} $$
I tried using DSolve for this differential equation, but it's not giving me any answer.
DSolve[
  v'[u] (2 u (1 - u v[u])/(1 + u v[u]) + u) ==
    v[u] (1 - u v[u])/(1 + u v[u]) + v''[u] (v[u]/2),
  v[u], u]

How do I solve this?
Edit
In case you want to solve the equation numerically, the boundary conditions are
$$v\left(\frac{1+\sqrt{4.9}}{2}\right) = \frac{-2}{1 + \sqrt{4.9}}$$
$$v\left(\frac{1-\sqrt{4.9}}{2}\right) = \frac{-2}{1 - \sqrt{4.9}}$$

A:
In case you want to solve the equation numerically, the boundary
  conditions are

Your boundary conditions are not consistent with the ODE.  Did you check?
Looking at this term in your ODE
 s = (1 - u*v[u])/(1 + u*v[u]);

Then you say one boundary condition is
 z = Sqrt[49/10];
 (v[(1 + z)/2] == -2/(1 + z)) // N

Lets check what happens to s at the above boundary condition
 s /. {u -> (1 + z)/2, v[u] -> -2/(1 + z)}

The same for the other boundary condition
 s /. {u -> (1 - z)/2, v[u] -> -2/(1 - z)}

So you can not solve it even numerically unless you fix the boundary conditions.


text:
Q: How to fix binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found) I am trying to use codecs.decode to decode from hex to utf - 8.
I get an error that there is a non-hexadecimal digit within my string, while I can't find anything like that and it's decoded successfully in sites like this one: https://onlineutf8tools.com/convert-hexadecimal-to-utf8
I've tried using different methods like bytes.fromhex()but I get the same error.

import codecs

hexString = "0x35303839372c312c333733002c003130003a3930"
utf = codecs.decode(hexString, "hex").decode('utf-8')

That's the expected outcome:
50897,1,373,10:90
The error I get:
binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)

A: You will need to remove the 0x prefix:
import codecs
hexString = "0x35303839372c312c333733002c003130003a3930"[2:]
utf = codecs.decode(hexString, "hex").decode('utf-8')


text:
Q: Javascript record keystroke timings I want to record the time between each keystroke (just one key to start with, the 'A' key) in millseconds.
After the user finishes his thing he can submit and check out the timings between each key stroke. Like:
1: 500
2: 300
3: 400
4: 500
5: 100
6: 50
7: 50
8: 25
I believe this is possible with Javascript, is it?

A: Sure:
var times = [];

// add an object with keycode and timestamp
$(document).keyup(function(evt) {
    times.push({"timestamp":evt.timeStamp,
                "keycode":evt.which})
});

// call this to get the string
function reportTimes() {
    var reportString = "";
    for(var i = 0; i < times.length - 1; ++i) {
         reportString += (i+1) + ": " + (times[i+1].timestamp - times[i].timestamp) + " ";
    }
    return reportString; // add this somewhere or alert it
}

I added the keycode just in case you wanted it later; it's not necessary for your exact problem statement.

Clarification from comments discussion:
The for loop only goes to up to times.length - 2 (since i is always strictly less than times.length - 1), so there is no issue about times[i+1] being outside the bounds of the array. For example, if you do five key presses and therefore have a times array with five elements (indexed from 0 to 4):
1st pass: times[1].timestamp - times[0].timestamp
2nd pass: times[2].timestamp - times[1].timestamp
3rd pass: times[3].timestamp - times[2].timestamp
4th pass: times[4].timestamp - times[3].timestamp

Then the loop terminates, because setting i to 4 triggers the termination condition:
= i < times.length - 1
= 4 < 5 - 1
= 4 < 4
= false  [i cannot be set to 4 by this loop]

Thus, times[i+1] is always a validly indexed element, because i is at most one less than the maximum index.


text:
Q: Is there a Stack Exchange WebSocket action for multiple tags? I'm developing an app to show all new questions for any tags that user is watching in realtime. So instead of using the REST API, I want to use the WebSocket at: wss://qa.sockets.stackexchange.com.
I'm able to observe for any tag with this action:
<siteid>-questions-newest-tag-<tagname>
And (looks like) I can observe as many as I need without limit. But when I send multiple actions for multiple tags, and IF a question has multiple tags of my choice together, The server respond me multiple times for a single question. For example javascript and jquery
My current solution is to keep the id of the responds and remove duplicates locally.
So THE QUESTION IS: Is there a built in way to remove duplicates? Like a unique action to get multiple tags or etc. Just like the original site itself.
-
Pseudo action desired just for more clarification:
<siteid>-questions-newest-any-tags-<tagname>;<tagname>;<tagname> // any
<siteid>-questions-newest-all-tags-<tagname>;<tagname>;<tagname> // all

A: No, there is no such way. The unofficial documentation doesn't list such a method, and if you check which websockets are active on a page showing the search results for [tag X] or [tag Y] you'll see it subscribes to two separate tag feed websockets:

The way you describe is also the way I do it for a system which notifies me of potentially interesting questions across the network.


text:
Q: How to bring JOption pop up window to front? I am working on my first project and it requires a JOption window to open for user input.  it works but the window is behind everything else so I have to minimize the editor to input the info.  How do I bring the window to the top?

A: I've never seen this behaviour. The only thing I can think of is to make sure you specifify the "owner" frame when you show the option pane.
Read the JOptionPane API and follow the link to the Swing tutorial on "How to Make Dialogs" for working examples.


text:
Q: Why is 'OraOLEDB.Oracle.1' provider is not registered on the local machine, when run in Debug Mode only? I have a C# source written by someone else, it has two configurations: Release and Debug both target Any CPU.
When I launch Release everything is great.  When I launch under Debug I get:
System.InvalidOperationException: The 'OraOLEDB.Oracle.1' provider is not registered on the local machine.

All the things I tried:

*

*I installed the 64bit 11.2 Oracle driver administrator package with all default settings.

*The oracle bin folder is setup in my path.

*All users have correct security permissions for the oracle folder.

*I can run tnsping and other commands just fine from a cmd prompt.

*The regsvr32 OraOLEDB11.dll was run successfully.

For some reason, it works if I target specifically x64 in debug mode.  Why does it look for an x86 driver when run under Any CPU?  Again it works fine under Release in Any CPU.


text:
Q: Why is "void operator delete(void* ptr, std::size_t size) noexcept;" not defined in gcc 4.9.0? As per the draft C++14 standard 18.2.1.1, the following global function is implicitly defined:
void operator delete(void* ptr, std::size_t size) noexcept;
However, the following code cannot be accepted by gcc 4.9.0 but can be compiled with clang 3.4.
int main()
{
    // error: invalid conversion from 'int' to 'void*'
    ::operator delete(new int, 1);
}

Is this a defect of gcc 4.9.0?

A:
gcc 4.9.0 which claims to completely support C++14

gcc 4.9.0 makes no such claims. The operator delete definition you're referring to was added as part of the sized deallocation proposal, which is as yet unimplemented in gcc.

A: According to OP by a previous revision:
The toolchain is gcc 4.9.0 rather than clang 3.4.


text:
Q: Help understand a line of code this is a weird question, but I read the following line of code:
Select[Flatten[Module[{x}, x = #;
       Join[x[[1]], #] & /@ x[[2 ;; -1]]] & /@ igraph, 1],
   Length@# > 1 &];

I was wondering if there is way to write this without the symbols or better if in a simpler way. I know that & means function and /@ means Map. But, I am struggling to write the code without these. Any help is appreciated. Many thanks

A: let's use curry
one by one.
Flatten[Module[{x}, x = #; Join[x[[1]], #] & /@ x[[2 ;; -1]]] & /@ igraph, 1] // Select[Length@# > 1 &];

igraph //
Map[
    Module[{x}, x = #;
    x[[2 ;; -1]] // Map[Join[x[[1]],#]&]
    ]&
] //
Flatten[# , 1]& //
Select[Length@# > 1 &];

now it seems easier to understand.
read it:

*

*take an element igraph,

*map a function on it.
this function is  Module[{x}, x = #; x[[2 ;; -1]] // Map[Join[x[[1]],#]&] ]&,

*Flatten[# , 1]& the result,

*select elements whose length > 1.

A: Mathematica's FullForm writes an expression without any abbreviations, not even ones you wish it would use:
Hold[Select[Flatten[Module[{x}, x = #;
       Join[x[[1]], #] & /@ x[[2 ;; -1]]] & /@ igraph, 1],
   Length@# > 1 &]] // FullForm
(*
Hold[Select[
  Flatten[
   Map[Function[
     Module[List[x],
      CompoundExpression[Set[x, Slot[1]],
       Map[Function[Join[Part[x, 1], Slot[1]]],
        Part[x, Span[2, -1]]]]]], igraph], 1],
  Function[Greater[Length[Slot[1]], 1]]]]
*)

The TreeForm[expr] and ExpressionTree[expr] make the nested [] easier to read in theory, but the tree quickly gets too large to read.
Here's a way to display the nested structure, in which I took the liberty of abbreviating a few commands:
nested // ClearAll;
nested // Attributes = {HoldAll};
myGrid = Grid[#, Alignment -> {Left, Top},
    Dividers -> {{{True, {False}}, 1 -> Pink}, False}] &;

(* Optional abbreviations *)
nested[e_Slot] := myGrid@{{HoldForm[e]}}; (* Slot[1]=#1, Slot[2]=#2... *)
nested[e_Part] := myGrid@{{HoldForm[e]}}; (* Part[x, 1]=x[[1]]... *)
(*nested[CompoundExpression[a__]]:=Module[{$list},
  myGrid[Riffle[
  Thread[{, nested /@ Hold[a] // Apply@List}],
  $list] /. $list -> {, ";"}]
];*)
nested[(h : Block | Module)[v_, a_]] :=
  myGrid[{ (* 1st arg List[x,y]={x,y} *)
    {Row[{h, "["}], SpanFromLeft},
    {, myGrid@{{HoldForm[v]}}},
    {, nested[a]},
    {"]"}}];
nested[(h : Set | SetDelayed)[v_, a_]] :=
  myGrid[{ (* v=... or v:=... *)
    {HoldForm[h[v, ""]], SpanFromLeft},
    {, nested[a]}}];

(* Main definitions *)
nested[h_[a___]] := myGrid[{
    {Row[{h, "["}], SpanFromLeft},
    Sequence @@ Thread[{, nested /@ Hold[a] // Apply@List}],
    {"]"}}];
nested[x_] := myGrid@{{HoldForm[x]}};

Each argument is spanned by a pink divider:
nested[
 Select[Flatten[Module[{x}, x = #;
      Join[x[[1]], #] & /@ x[[2 ;; -1]]] & /@ igraph, 1],
  Length@# > 1 &]
 ]

Appendix: ...in a simpler way
It occurred to me that the OP wants the code refactored, which I missed at first.
The most egregious obfuscation is the use of Module to localize the argument #1.  It seems the author was not familiar with Function[{x}, body].  One can simply change Module to Function and get rid of the x = #; and the trailing &, preferably adding a comment:
Block[{igraph =
  {{{1, 11}, {2}, {3}}, {{4}, {5, 10}, {6}}, {{7}, {8}, {}}}},

 Select[
  Flatten[
   Function[{x}, (* join First list in x to Rest of lists in x *)
     Join[First[x], #] & /@ Rest[x]
     ] /@ igraph, (* for each list in igraph *)
   1],
  Length@# > 1 &]

 ]

(*  {{1, 11, 2}, {1, 11, 3}, {4, 5, 10}, {4, 6}, {7, 8}}  *)

Alternatively, one could name the function and take advantage of Mathematica's pattern-matching and term-rewriting capabilities:
joinFirstToRest[{x1_, x2___}] := Join[x1, #] & /@ {x2};

Block[{igraph =
  {{{1, 11}, {2}, {3}}, {{4}, {5, 10}, {6}}, {{7}, {8}, {}}}},

 Select[
  Flatten[joinFirstToRest /@ igraph, 1],
  Length[#] > 1 &]

 ]

If one is looking for a procedural equivalent to joinFirstToRest /@ igraph, which is the same as Map[joinFirstToRest, igraph] ("I am struggling to write the code without these"), I offer this for educational purposes:
Table[joinFirstToRest[x], {x, igraph}]

(Change Map to Table, pick an iterator x and plug it into the function and the list-iterator form for Table.)  The expression inside the OP's Flatten[expr, 1] becomes, after simplifying Function[{x}, body][x] to just body, the following:
Table[Join[x[[1]], #] & /@ x[[2 ;; -1]]], {x, igraph}]

or, transforming Map again,
Table[
 Table[Join[x[[1]], y], {y, x[[2 ;; -1]]}],
 {x, igraph}]

which could be combined into
Table[Join[First@x, y], {x, igraph}, {y, Rest@x}]

The 2D Table form also reveals why the next step might be to Flatten it one level.  I usually like Map better than Table, but Table seems easier to read here. I still prefer First@x to First[x] and certainly Rest@x to x[[2 ;; -1]], especially when they are themselves adjacent to brackets and braces.


text:
Q: Spring MongoTemplate updateMulti with Limit? I'm using Spring Data's MongoTemplate to update multiple documents with a single query. I need to be able to limit the number of documents I update per call. For reasons unclear to me the limit isn't working:
Query query = new Query(
    Criteria.where( "foo" ).is( bar )
    .and( "status" ).is( 1 ) );
query.limit( 10 );

Update update = new Update();
update.set( "status", 2 );

WriteResult result = mongoTemplate.updateMulti( query, update, "bazCollection" );

logger.info( result.getN() + " documents updated" );

result.getN() always returns the total number of documents that meet the Criteria and is ignoring the limit, and all documents meeting the criteria are modified.
Is there a reason this isn't working?
Is there a better approach to accomplish the same thing?

A: you can't use an updateMulti with limit but how to make atomic update status on a limited set of documents?
I used the following pattern to avoid concurrent write issue (concurrent change status more than one time on a given document):

*

*find target document id's to update using limit and using status condition

*updateMulti with target document id's and status as condition : target doc ids may have been already updated by concurrent thread so we need to set status as condition here again. This query sets also an updateTime in an update field

*find updated document id's : rely on document id's + updateTime.

Please let me know if there is a better solution / pattern to do that.


text:
Q: Why does the result from the camera intent crash, but only on a Samsung Galaxy4? I have a vehicle inspection application that is working, except on a Samsung Galaxy 4. Using a camera intent, the user takes a picture, selects ok, then onActivityResult, it crashes. As you can see, I am using iText to create a PDF later in the code, but I create the iText Image. Does anyone have a clue on this specific issue???
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    tireTreadImageView = (ImageView) findViewById(id.tire_tread_image);
    insideVanCleanImageView = (ImageView) findViewById(id.inside_van_clean_image_view);
    windshieldConditionImageView = (ImageView) findViewById(id.windshield_image_view);
    Bitmap bitmap;
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    File f;
    ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();

    if (resultCode == RESULT_OK) {

        switch (requestCode) {
            case TIRE_TREAD_CAMERA_INTENT:
                f = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "temp_tire_tread.jpg");
                bitmap = BitmapFactory.decodeFile(f.toString(), bitmapOptions);
                //imageCaptured = (Bitmap) data.getExtras().get("data");
                tireTreadImageView.setImageBitmap(bitmap);
                tireTreadImage = bitmap;

                tireTreadImage.compress(Bitmap.CompressFormat.JPEG, 15, bmpStream);

                try {
                    tireTreadCellImage = Image.getInstance(bmpStream.toByteArray());
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                break;

            case VAN_CLEAN_CAMERA_INTENT:
                f = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "temp_van_clean.jpg");
                bitmap = BitmapFactory.decodeFile(f.toString(), bitmapOptions);
                //imageCaptured = (Bitmap) data.getExtras().get("data");
                insideVanCleanImageView.setImageBitmap(bitmap);
                insideVanCleanImage = bitmap;

                insideVanCleanImage.compress(Bitmap.CompressFormat.JPEG, 15, bmpStream);

                try {
                    insideVanCleanCellImage = Image.getInstance(bmpStream.toByteArray());
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                break;

            case WINDSHIELD_CAMERA_INTENT:
                f = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "temp_windshield.jpg");
                bitmap = BitmapFactory.decodeFile(f.toString(), bitmapOptions);
                //imageCaptured = (Bitmap) data.getExtras().get("data");
                windshieldConditionImageView.setImageBitmap(bitmap);
                windshieldImage = bitmap;

                windshieldImage.compress(Bitmap.CompressFormat.JPEG, 15, bmpStream);

                try {
                    windshieldConditionCellImage = Image.getInstance(bmpStream.toByteArray());
                } catch (BadElementException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                break;
        }
    }
    bmpStream.reset();
}

A: As Sebastien said, you should try to find more information about this issue. There are some discussions about related questions/answers here:

*

*https://stackoverflow.com/a/15287164/5837758

*https://stackoverflow.com/a/11351580/5837758

*https://kevinpotgieter.wordpress.com/2011/03/30/null-intent-passed-back-on-samsung-galaxy-tab/
Hope it helps,


text:
Q: Python Convert Counters into DataFrame Columns I haven't been able to find an answer here specific to my issue and I'm wondering if I could get some help (apologies for the links, I'm not allowed to embed images yet).
I have stored Counter objects within my DataFrame and also want them added to the DataFrame as a column for each counted element.
Beginning data
data = {
    "words": ["ABC", "BCDB", "CDE", "F"],
    "stuff": ["abc", "bcda", "cde", "f"]
}
df = pd.DataFrame(data)

Preliminary Data Frame
patternData = {
    "name": ["A", "B", "C", "D", "E", "F"],
    "rex": ["A{1}", "B{1}", "C{1}", "D{1}", "E{1}", "F{1}"]
}
patterns = pd.DataFrame(patternData)

Pattern DataFrame
def countFound(ps):
    result = Counter()
    for index, row in patterns.iterrows():
        findName = row['name']
        findRex = row['rex']
        found = re.findall(findRex, ps)
        if (len(found) > 0):
            result.update({findName:len(found)})
    return result

df['found'] = df['words'].apply(lambda x: countFound(x))

Found DataFrame
Desired Results

words
stuff
found
A
B
C
D
E
F

ABC
acb
{'A': 1, 'B': 1, 'C': 1}
1
1
1
0
0
0

BCD
bcd
{'B': 1, 'C': 1, 'D': 1}
0
2
1
1
0
0

CDE
cde
{'C': 1, 'D': 1, 'E': 1}
0
0
1
1
1
0

F
f
{'F': 1}
0
0
0
0
0
1

A: A Counter behaves a lot like a dictionary. Calling pd.DataFrame on a list of dictionaries will give you the matrix of counted values:
found = df['words'].apply(countFound).to_list()
pd.concat([
    df.assign(found=found),
    pd.DataFrame(found).fillna(0).astype("int")
], axis=1)

A: You can use json_normalize:
df.join(pd.json_normalize(df['found']).fillna(0, downcast='infer'))

Output:
  words stuff                     found  A  B  C  D  E  F
0   ABC   abc  {'A': 1, 'B': 1, 'C': 1}  1  1  1  0  0  0
1  BCDB  bcda  {'B': 2, 'C': 1, 'D': 1}  0  2  1  1  0  0
2   CDE   cde  {'C': 1, 'D': 1, 'E': 1}  0  0  1  1  1  0
3     F     f                  {'F': 1}  0  0  0  0  0  1

You can also directly get the columns without your custom function. For this use a dynamically crafted regex with named capturing groups and str.extractall:
regex = ('(?P<'+patterns['name']+'>'+patterns['rex']+')').str.cat(sep='|')
# (?P<A>A{1})|(?P<B>B{1})|(?P<C>C{1})|(?P<D>D{1})|(?P<E>E{1})|(?P<F>F{1})

df2 = df.join(df
 ['words']
 .str.extractall(regex)
 .groupby(level=0).count()
 )

Or variant without named capturing groups and settings up the column names later:
regex = ('('+patterns['rex']+')').str.cat(sep='|')
# (A{1})|(B{1})|(C{1})|(D{1})|(E{1})|(F{1})

print(df.join(df
 ['words']
 .str.extractall(regex)
 .set_axis(patterns['name'], axis=1)
 .groupby(level=0).count()
 ))

Output:
  words stuff  A  B  C  D  E  F
0   ABC   abc  1  1  1  0  0  0
1  BCDB  bcda  0  2  1  1  0  0
2   CDE   cde  0  0  1  1  1  0
3     F     f  0  0  0  0  0  1


text:
Q: Как вытащить все комментарии из текстового файла на Linux? Перебрал великое множество разных утилит на Linux, в итоге так ни к чему и не пришёл. Они все валятся на многострочных комментариях. Остановился на grep с ключом -E. Корректен ли такой способ получения всех комментариев в си-стиле из файла?
Посоветуйте, пожалуйста, подходящую утилиту и если надо,то регулярку.

A: Можно воспользоваться
grep -Eoz "/\*+[^*]*\*+([^/*][^*]*\*+)*/"

Опции

*

*E - задает синтаксис регулярок POSIX ERE (использует более соврменный и понятный большинству синтаксис регулярок, где + это квантификатор, а не знак +)

*o - задает режим выдачи найденных совпадений, а не целых строк

*z - делает возможным поиск совпадений между несколькими строками.

Регулярное выражение

*

*/ - знак /

*\*+ - 1 и более знаков *

*[^*]* - 0 и более знаков, отличных от *

*\*+ - 1 и более знаков *

*([^/*][^*]*\*+)* - 0 и более повторов

*

*[^/*] - символ, отличный от / и *

*[^*]* - 0 и более знаков, отличных от *

*\*+ - 1 и более знаков *

*/ - знак /


text:
Q: how to customize the dataset on a primeng bar graph I'm using primeng on an angular and I want to create a bar graph where the last 2 horizontal bars are colored differently.
At the moment the last 2 are being wrapped around and interpreted as dogs and cats
My question is, how would I edit the graph so that the two orange bars on dog and cat are on tiger and lion?
For some reason StackOverflow is not letting me post a picture so here is the link to an image hosting site I uploaded the example to:
https://ibb.co/jZyxddC
component code:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-status-logs-graph',
  templateUrl: './status-logs-graph.component.html',
  styleUrls: ['./status-logs-graph.component.scss']
})
export class StatusLogsGraphComponent implements OnInit {

  basicData: any;
  basicOptions: any;

  constructor() {
      this.basicData = {
    labels: ['dog', 'cat', 'hamster', 'lizard', 'tiger', 'lion'],
    datasets: [
        {
            label: 'Domestic Animals',
            backgroundColor: '#42A5F5',
            data: [ 32, 54, 21, 11]
        },
        {
            label: 'Wild Animals',
            backgroundColor: '#FFA726',
            data: [28, 48]
        }
    ]
};
 }

  ngOnInit(): void {

}
}

A: Primeng uses chartjs under the hood. You can find its documentation here.
With chartjs you can define the color of each bar of your chart individually. If you put all the animals in the same dataset and then define the colors for each of the animals, you come close to what you want to achieve. The only downside is that you should hide the legend, since it will just say "Domestic animals", since you are only using one dataset. (You can of course create your own legend using html/css.) Here is a full example:

var basicData = {
    labels: ['dog', 'cat', 'hamster', 'lizard', 'tiger', 'lion'],
    datasets: [
        {
            data: [ 32, 54, 21, 11, 28, 48],
            backgroundColor: [
                '#42A5F5',
                '#42A5F5',
                '#42A5F5',
                '#42A5F5',
                '#FFA726',
                '#FFA726'
            ]
        }
    ]
};
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: basicData,
    options: {
        plugins: {
            legend: {
                display: false
            }
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.4.1/dist/chart.min.js"></script>
<canvas id="myChart"></canvas>

Now, this is not very scalable. A better approach might be to put all data in an array and combine the dataset on the fly. This way, you can always easily add an animal. See this example:

var animals = [
    {
        name: 'dog',
        data: 32,
        type: 'domestic'
    },
    {
        name: 'cat',
        data: 54,
        type: 'domestic'
    },
    {
        name: 'hamster',
        data: 21,
        type: 'domestic'
    },
    {
        name: 'lizard',
        data: 11,
        type: 'domestic'
    },
    {
        name: 'tiger',
        data: 28,
        type: 'wild'
    },
    {
        name: 'lion',
        data: 48,
        type: 'wild'
    }
];
var labels = [];
var data = [];
var colors = [];
for(var i = 0; i < animals.length; i++){
    labels.push(animals[i].name);
    data.push(animals[i].data);
    if(animals[i].type === 'domestic'){
        colors.push('#42A5F5');
    }
    else{
        colors.push('#FFA726');
    }
}
var basicData = {
    labels:labels,
    datasets: [
        {
            data: data,
            backgroundColor: colors
        }
    ]
};
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: basicData,
    options: {
        plugins: {
            legend: {
                display: false
            }
        }
    }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.4.1/dist/chart.min.js"></script>
<canvas id="myChart"></canvas>

A: Use the Chart.js skipNull property, and set it equal to true.
(PrimeNG's charts all extend/use Chart.js).

A: Did you mean do you want to horizontal separate bar charts for domestic animal and wild animals and domestic animal should be different colors?
In that case you can use Ngx-charts. You can get an idea using below link
https://swathisprasad.medium.com/building-data-visualization-with-angular-and-ngx-charts-375942d49fd6


text:
Q: How can I use a packaged (exported) stylesheet with saxon 9.7+ s9api? Starting with Saxon 9.7 we have to use a different s9api procedure to "import" a packaged stylesheet. Here, Michael says "Stylesheet packages can ... be imported ... using ... the s9api API." He then referred to these details.
As I read it, hoping that it would be simple, I locked in on this:

A stylesheet export file ... is accepted by any Saxon interface that accepts a source stylesheet.

So, I created this MCV example:
import java.io.*;
import net.sf.saxon.Configuration;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
public class test {
    public static void main (String args[]) throws Exception {
        Processor saxProc = new Processor(false);
        Configuration saxCfg = saxProc.getUnderlyingConfiguration();
        XsltCompiler saxComp = saxProc.newXsltCompiler();
        File xslmain = new File(args[0]);
        Source xsl = new StreamSource(xslmain);
        XsltExecutable saxExe = saxComp.compile(xsl);
    }
}

Executed like this (using 9.9.1.7J for ee, pe, and he) no exception is thrown:
$ javac -classpath saxon9pe.jar test.java
$ java -classpath .:saxon9he.jar test something.xsl

But if I package up something.xsl (i.e., use EE to export it to an xml file) and execute the MCV like this, then an exception is thrown:
$ java -classpath .:saxon9he.jar test something-exported.xml
Error
  SXPK0002: Cannot load expression with tag indexedFilter2. The stylesheet uses Saxon-EE features
Exception in thread "main" net.sf.saxon.s9api.SaxonApiException: Cannot load expression with tag indexedFilter2. The stylesheet uses Saxon-EE features

Shouldn't I be able to package an xsl file using EE, distribute HE, and read the packaged stylesheet using HE to perform transformations? If yes, how?

A: Try compiling it with -target:HE. In principle this should stop Saxon-EE generating constructs that the HE run-time won't recognize.
I have to say though, this isn't very thoroughly tested. It may also be necessary to disable selected optimizations using the -opt option.


text:
Q: Based on this QQ-plot, does this looks approximately normal? based on the attached QQ-plot, can I say that the distribution is approximately normal? The results for Shapiro-Wilk test is p-value = 0.1334 but the sample size is small (only 12 as they are observations for each month) so I am not sure if its suitable to use the results from Shapiro test.

A: No, it is not. As the line has a different slope by the line of y = x, it means that this distribution has a different skewness than the normal distribution.


text:
Q: Typescript : AngularJS retrieving a result object I have a AngularJS service in Typescript that makes a get https call returns some data.
My results is a child object of the response.data as follows response.data.Result.
How do I get access to it? I cannot do response.data.Result as I get compile time error where the response.data defined under IHttpPromiseCallbackArg<T> does not have the result property.
 class ApplicationService implements IApplicationService {
        private webApiUrl;
        static $inject = ['$http'];

        constructor(private $http: ng.IHttpService) {
            this.webApiUrl = 'http://localhost';
            this.$http = $http;
        }

        getApplications(): ng.IPromise<IApplication[]> {
            return this.$http.get(this.webApiUrl + '/api/applications')
                .then((response: ng.IHttpPromiseCallbackArg<IApplication[]>): IApplication[]=> {
                return <IApplication[]>response.data;
            });
        }
    }

A: After this.$http.get(this.webApiUrl + '/api/applications'), try changing from ng.IHttpPromiseCallbackArg<IApplication[]> to { data: { Result: IApplication[] } } type.
class ApplicationService implements IApplicationService {
    private webApiUrl;
    static $inject = ['$http'];

    constructor(private $http: ng.IHttpService) {
        this.webApiUrl = 'http://localhost';
        this.$http = $http;
    }

    getApplications(): ng.IPromise<IApplication[]> {
        return this.$http.get(this.webApiUrl + '/api/applications')
        .then((response: { data: { Result: IApplication[] } }): IApplication[]=> {
            return response.data.Result;
        });
    }
}


text:
Q: Kerberos and multiple SPNs I managed to setup Kerberos authentication for 1 server and is up and running ok. Now I have a project where I have to add another server to Kerberos configuration as follow:
1) AD server
2) server1 where service is running
3) server2 where same service will be running
so I executed setspn command to assing both to single "spn" user:
setspn -s serviceX/server1.domain.com@DOMAIN.COM spn
setspn -s serviceX/server2.domain.com@DOMAIN.COM spn
Then I executed comman ktpass:
ktpass -princ serviceX/server1.domain.com@DOMAIN.COM -ptype KRB5_NT_PRINCIPAL -crypto AES256-SHA1 -mapuser serviceX\spn -out C:\keytab +rndPass
What should I do next to make it work?
How to execute ktpass for server2?
When I tried same command for server2 I'm getting Warning:
Warning: Failed to set UPN serviceX/server2.domain.com ptype 1 vno 10 etype 0x12
kinits to "serviceX/server2.domain.com" will fail.
How do you guys setup kerberos authentication for same service but on different servers?
Do you create 2 spn users and 2 keytabs?
I think I need to have everything in 1 keytab as the service requires it.
Any help?

A: You can run serviceX on the two different servers using the same keytab by using an SPN tied to a user account in the Directory rather than to each of the servers.  To do this, you tie the SPN to a virtual server name (aka a "VIP") instead of a real one.  We do this all the time at my current organization.  So since the SPN would use a virtual server name in DNS, you just configure the load-balancer to send any queries for that virtual name to the real servers behind it "answering" to that name.  So in this case, instead of worrying about having unique keytabs for both server1 and server2, your just create one keytab for what I'll refer to as server-vip, and then copy that same keytab to both servers.  If you don't have a load balancer then you can do this just using DNS round robin.  So the below example would be your new keytab creation syntax, notice how only one thing changes.  Another reason why this is good is because it is resilient to to server changes.  When you eventually decommission server1 and server2, you can easily just copy the keytab to server3 and server4 when that day comes.

ktpass -princ serviceX/server-vip.domain.com@DOMAIN.COM -ptype
  KRB5_NT_PRINCIPAL -crypto AES256-SHA1 -mapuser serviceX\spn -out
  C:\keytab +rndPass

A: friend...
when you try bind the SPN:
serviceX/server-vip.domain.com@DOMAIN.COM

with the UPN
spn

The error: kinits to "serviceX/server2.domain.com" will fail. indicate some problem, but not exactly where or how. I had the same problem today, but another log revealed the main cause of the error:
Failed to set property 'userPrincipalName'
When we try generate the keytab with ktpass, this message is displayed, what we don't imagine, is that the UPN object have so many attributes, one of them is UserPrincipalName. So why we cant set the attribute UserPrincipalName with "spn" value? because it already configured in another UPN attribute! unhappiness you will need verify all attributes of yours UPN, searching for "spn" value.
you can use adsiedit to manual search:
adsiedit.msc

or make a loop with users searching for userPrincipalName attribute:
$users = get-aduser -filter *
foreach ($var in $users) { $var | select Name, UserprincipalName | fl }

I solved my problem finding my "UserPrincipalName" attribute wrong configured in another UPN.
► Each UserPrincipalName need be configured with the same name of your UPN.
UPN=s_user_http, then UserPrincipalName=s_user_http@YOUR_DOMAIN, verify this!
answering your question:
one UPN can be a multiples SPN, but its dangerous, if you increment the kvno accidentally, all anothers keytabs will be invalidate. Use one UPN for each SPN.
I hope this help.


text:
Q: How do I post an image using Koala gem? I'm using the Koala gem to post images to the Facebook wall with the put_object method. The problem I'm having is that the images show up as thumbnails on the wall (with a caption) instead of the larger image that I'm expecting. When you click on the thumbnail, I'm expecting the photo to pop open in Facebook's photo viewer, but it simply directs me to the URL of the image I specified. This seems more like the behavior I'd expect when posting a link to the wall. I've also tried using post_picture with no success. Here is a screenshot of what I'm expecting: http://cl.ly/image/472a2H333z13
My stream permissions include the following:
read_stream,offline_access,manage_pages,publish_stream,create_event,rsvp_event,sms,user_photos,friends_about_me,friends_status,friends_activities,friends_likes,friends_interests,read_insights,friends_photos

The following code works but not as expected - here is a screenshot of how an image posted in using put_object appears on the timeline: http://cl.ly/image/1x3X1K0k2l2D
put_object('me', 'feed', :message => 'this is the message', :name => 'this is the caption', :picture => 'http://www.socialvolt.com/img/producttour/listen.png', :source => 'http://www.socialvolt.com/img/producttour/ssPublish.jpg')

This code doesn't work at all:
put_picture('me', 'feed', :message => 'this is the message', :name => 'this is the caption', :picture => 'http://www.socialvolt.com/img/producttour/listen.png', :source => 'http://www.socialvolt.com/img/producttour/ssPublish.jpg')

I also can't find any difference between :picture and :source.
Can anyone help me figure out what I'm doing wrong?

A: Here is the code.
 graph = Koala::Facebook::API.new(cookies[:acess_token])
 begin
   graph.put_picture(
                     "https://dl.dropboxusercontent.com/u/71317935/banners/coy_copper.jpg",
                     "image/png",
                     {:message => "introduces Some information"}
                   )
 rescue Exception => e
   render :text => e.message and return
 end

A: Off the top of my head, you may need a larger photo. More specifically, I think the width needs to be at least 480px.
The images in your code seem to be less than 480px:
http://www.socialvolt.com/img/producttour/listen.png
http://www.socialvolt.com/img/producttour/ssPublish.jpg
This comes from experience with User Generated Photos. You're not really using Open Graph Actions, so I have no idea if Facebook applies the same rules for this to generic photo uploads.


text:
Q: how to do event based serial port reading in c? i want to read serial port when there is some data present i mean on the event when data arrives only then i will read serial port instead of continuously reading the port i have this code for continuous reading the port how can i make it event based.
thanx in advance.
while(1)
{
   bReadRC = ReadFile(m_hCom, &byte, 6, &iBytesRead, NULL);
   printf("Data Recieved Through Serial port and no. of Bytes Recieved is    %d",iBytesRead);
 }

A: According to MSDN you can use the WaitCommEvent() operation on your serial port handle.
Also, this article gives a nice introduction into the topic.

A: This looks like WinAPI, and I'm not exactly an expert at that, but you should be able to set the port to blocking mode. This will cause the read call to block (wait on that line) until there's data available.


text:
Q: tornado - WebSocketClientConnection - How to catch and handle connection failures? I am a Tornado and also Websocket newbie. There are many resources how to implement a websocket server application with Tornado. However, I haven't found a complete example that contains a websocket client application built on top of Tornado.

Server Application (server.py)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import tornado.web
import tornado.websocket
import tornado.ioloop
import tornado.options

from tornado.options import define, options

define("port", default=3000, help="run on the given port", type=int)

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [(r"/", MainHandler)]
        settings = dict(debug=True)
        tornado.web.Application.__init__(self, handlers, **settings)

class MainHandler(tornado.websocket.WebSocketHandler):
    def check_origin(self, origin):
        return True

    def open(self):
        logging.info("A client connected.")

    def on_close(self):
        logging.info("A device disconnected")

def main():
    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

Client Application (client.py):
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tornado.ioloop import IOLoop
from tornado.websocket import websocket_connect

if __name__ == "__main__":
    ws = websocket_connect("ws://localhost:3000")
    IOLoop.instance().start()

Problems & Questions
I don't have any problems with server application. However, I can't say same thing for client application. Why?

*

*If server goes down, client application doesn't react. It does not say "Hey, server is down buddy.". I write my own WebSocketClientConnection class (inherited by the original) and also websocket_connect function (same function, but this one uses my WebSocketClientConnection class). I override on_connection_close method in my WebSocketClientConnection class, so I can catch "server down on middle of the connection" failure. However, I cannot make it reconnect. How do I make it reconnect to server?

*If server is already down before the connection, client application does not raise anything and seems perfectly. I don't know how to catch that failure. How do I catch this connection failure?

My WebSocketClientConnection class:
class MyWebSocketClientConnection(tornado.websocket.WebSocketClientConnection):
    def on_connection_close(self):
        super(MyWebSocketClientConnection, self).on_connection_close()
        print "connection closed"

Thanks.

A: By the way, after I figured out, I did write an example Tornado WebSocket client/server pair to demonstrate how to do it.
https://github.com/ilkerkesen/tornado-websocket-client-example
I hope it helps someone.

A: websocket_connect returns a Future; to see whether it succeeded or failed you must examine the Future (probably by yielding it in a coroutine). Furthermore, after establishing the connection you should go into a read_message loop. Even if you don't expect the client to send any messages, you should still call read_message: this is how you will connections that are closed after being established (read_message will return None).
@gen.coroutine
def my_websocket_client(url):
    ws = yield websocket_connect(url)
    while True:
        msg = yield ws.read_message()
        if msg is None: break
        # do stuff with msg


text:
Q: Export each column of a pandas dataframe as txt How can I export each column of a pandas dataframe as a new txt file with the name of the txt.file being the colum name and each cell entry being seperated by a new line "\n"?

A: Use Series.to_csv in loop:
for c in df.columns:
    df[c].to_csv(c + '.txt', index=False)


text:
Q: Buffer along a route I'm using Googlemaps service to plot some marker on the map. All markers are stored in a postgresql table, named "locations" and that has a location column (data type to geometry).
When the user clicks on the markers a route is created between them.
My question is: how can I generate a buffer (with a limit of 10km along route) and select all my locations inside the buffer. I`m really new in postgis.
P.S. This link inspired me but without success
Thanks!

A: SELECT ST_Astext(geom) FROM "locations" WHERE ST_Contains( ST_Buffer( St_GeomFromText( 'LINESTRING( 6 52, 6.5 53, 7 54 )', 4326 ), 10000 ), geom )

*

*ST_Buffer(
geom, radius ) creates a 10km buffer. Im using a linestring as
example. Second argument is in meters when using SRID 4326. Calculations are in the Spatial Reference System of this Geometry.

*ST_Contains(
geomA, geomB ) Returns true if and only if no points of B lie in
the exterior of A, and at least one point of the interior of B lies
in the interior of A.

Don't hesitate to ask me if you need more help!
edit:
SRID 4326 is NOT measuring in meters (see here).
Besides that, it's better (faster) to use ST_DWithin. There is a note in the ST_Buffer documentation:

People often make the mistake of using this function to try to do
  radius searches. Creating a buffer to to a radius search is slow and
  pointless. Use ST_DWithin instead.

If you would like to measure in meters its better to use geography instead of geometry:
SELECT ST_Astext(geom) FROM "locations" WHERE ST_DWithin( ST_GeographyFromText( 'LINESTRING(48.85523 2.36179,48.85556 2.36205,48.85591 2.36226,48.857 2.36288,48.85806 2.36362,48.85834 2.36382,48.85818 2.36434,48.85817 2.36444,48.85817 2.36448,48.85882 2.3645,48.86 2.36454,48.86144 2.3646,48.86178 2.3646,48.86184 2.36458,48.86187 2.36455,48.86193 2.36446,48.86199 2.36455,48.86205 2.3646,48.8621 2.36464,48.86277 2.36466,48.86367 2.36469,48.86459 2.36583,48.8647 2.36577)' ), geom::geography, 10000 );

It transforms the points to geographic points and the input is a geographic linestring. ST_GeographyFromText() description:

Returns a geography object from the well-known text representation.
  SRID 4326 is assumed.

Good luck!
edit2:
If you want to extract the polygon with the buffer area u can use this query:
SELECT ST_Astext(geom) as "point", ST_AsText( ST_Buffer( "linestring", 10000 ) ) as "buffer" FROM "locations", ST_GeographyFromText( 'LINESTRING(48.85523
2.36179,48.85556 2.36205,48.85591 2.36226,48.857 2.36288,48.85806 2.36362,48.85834 2.36382,48.85818 2.36434,48.85817 2.36444,48.85817 2.36448,48.85882 2.3645,48.86 2.36454,48.86144 2.3646,48.86178 2.3646,48.86184 2.36458,48.86187 2.36455,48.86193 2.36446,48.86199 2.36455,48.86205 2.3646,48.8621 2.36464,48.86277 2.36466,48.86367 2.36469,48.86459 2.36583,48.8647 2.36577)' ) as "linestring" WHERE ST_DWithin("linestring", geom::geography, 10000 );


text:
Q: Query to find places near to me (Google Map) For the purposes of my application, i am using google maps so that:
A user will mark at the map the place where he stays (it is stored to the db). Then when he views the map again, it should show other users who stay near to him.
The coordinates are stored at a db field of users named eg coords, at this form: 22.515578,33.265897 (latitude,longitude)
What should be the query so that to find all marks which are +/- 1 (or any other distance) from him?? (Eg if he is at 22.515578,33.265897 then it should search for others which are eg at 21.515578,32.265897 or 23.515578,34.265897)
Thanks in advance!

A: This can help you.
For example here let given latitude and longitude is 32, -122 and distance is less then 25 miles.
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
FROM geocodeTable HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

A: Don't reinvent the wheel.If you are using mysql try the spatial extensions and the spatial functions between geometries(i.e. distance).if you try to do this manually than you must go another way.Cheers


text:
Q: on/off auto scroll toggle to owl carousel inside a shortcode wordpress I have here is My function that shows owl carousel
function showpost_func( $atts ) {
    $atts = shortcode_atts( array(
        'category' => '',
        'show' => '15',
    ), $atts, 'showpost' );

    ob_start();

    if ($atts['category']) {
        $cc_cat = esc_attr($atts['category']);
        $cc_cat_not = '';
    } else {
        $cc_cat = '';
        $cc_cat_not = '102';
    }

    $the_query = new WP_Query( array(
        'post_status' => 'publish',
        'post_type' => 'post',
        'category_name' => $cc_cat,
        'orderby' => 'date',
        'order' => 'DESC',
        'posts_per_page' => esc_attr($atts['show']),
        'category__not_in' => $cc_cat_not,
        'ignore_sticky_posts' => 1
    ) );

    if ( $the_query->have_posts() ) {
        echo '

';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();

            $featured_video = get_field('video_url');

            if ( has_post_thumbnail() ) {
                $cimg_url = get_the_post_thumbnail_url();
            } else {
                $cimg_url = get_stylesheet_directory_uri().'/images/no-image.jpg';
            }

            if (has_category('video',$post->ID)) {
                echo '
'; ?>

<iframe src="https://player.vimeo.com/video/<?=$featured_video?>?color=a894ae&title=0&byline=0&portrait=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen>

                <?php
                echo '
'.get_the_title().'

';
            } else {
                echo '

'.get_the_title().'

';
            }

        }
        echo '

';
    } else {
        // no posts found
    }
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode( 'showpost', 'showpost_func' );

USAGE: [showpost category="category-slug" show="15"]
and here is my owl carousel js code
jQuery('.owl-carousel').owlCarousel({
    autoplay:true,
    loop:false,
    rewind:true,
    margin:20,
    nav:true,
    responsive:{
        0:{
            items:3
        },
        600:{
            items:3
        },
        1000:{
            items:4
        }
    }
})

My question is How to have an option per shortcode to make the autoscroll stop
like this I am showing two shortcodes, and the first shortcode should not be scrolling and the second one will scroll
[showpost category="category-slug" show="15" autoscroll="stop"]
[showpost category="category-slug" show="15"]

A: This is what I did, sorry I had to share what I did, I added another shortcode attribute
'autoscroll' => 'false'

I also added a class to the main wrapper so that the script will point to its main wrapper

below is the working code
//[showpost category="category-slug" show="15" autoscroll="true/false"]
function showpost_func( $atts ) {
    $atts = shortcode_atts( array(
        'category' => '',
        'show' => '15',
        'autoscroll' => 'false'
    ), $atts, 'showpost' );

    ob_start();

    if ($atts['category']) {
        $cc_cat = esc_attr($atts['category']);
        $cc_cat_not = '';
    } else {
        $cc_cat = '';
        $cc_cat_not = '102';
    }

    $the_query = new WP_Query( array(
        'post_status' => 'publish',
        'post_type' => 'post',
        'category_name' => $cc_cat,
        'orderby' => 'date',
        'order' => 'DESC',
        'posts_per_page' => esc_attr($atts['show']),
        'category__not_in' => $cc_cat_not,
        'ignore_sticky_posts' => 1
    ) );

    if ( $the_query->have_posts() ) {
        echo '

';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();

            $featured_video = get_field('video_url');

            if ( has_post_thumbnail() ) {
                $cimg_url = get_the_post_thumbnail_url();
            } else {
                $cimg_url = get_stylesheet_directory_uri().'/images/no-image.jpg';
            }

            if (has_category('video',$post->ID)) {
                echo '
'; ?>

<iframe src="https://player.vimeo.com/video/<?=$featured_video?>?color=a894ae&title=0&byline=0&portrait=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen>

                <?php
                echo '
'.get_the_title().'

';
            } else {
                echo '

'.get_the_title().'

';
            }

        }
        echo '

';
    } else {
        // no posts found
    }
?>

<?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode( 'showpost', 'showpost_func' );


text:
Q: Suppose $t, u, v, w \in \mathbb{R}^3$. If $(t \times u) \times (v \times w) = 0$, are $t,u,v,w$ on the same plane?
Suppose $t, u, v, w \in \mathbb{R}^3$. If $(t \times u) \times (v \times w) = 0$, are $t,u,v,w$ on the same plane?

My Answer
No. Let $p_1$ be the plane described by $x + y + z = 3$ and $p_2$ the plane described by $x + y + z = 4$. Then the planes do not intersect but they have the same norm, $n = (1,1,1)$. Letting $t,u \in p_1$ and $v,w \in p_2$, it follows that they are not on the same plane but
$$(t \times u) \times (v \times w) = n \times n = 0$$

A: If $t$ and $u$ are linearly dependent, then it is trivial that
$$(t\times u)\times (v\times w)=0\,.\tag{*}$$
If $v$ and $w$ are linearly dependent, then (*) is obviously true.  From now on, suppose that $t$ and $u$ are linearly independent, and $v$ and $w$ are also linearly independent.
If the span of $t$ and $u$ coincides with the span of $v$ and $w$, then let $p$ denote the span of all vectors $t$, $u$, $v$, and $w$.  Thus, both $t\times u$ and and $v\times w$ are vectors normal to $p$.  Hence, $t\times u$ and $v\times w$ are linearly dependent, whence (*) is true.
Suppose now that the span of $t$ and $u$ does not coincide with the span of $v$ and $w$.  Therefore, the span of $t$, $u$, $v$, and $w$ is the whole $\mathbb{R}^3$, which is a $3$-dimensional vector space.  Thus, one of the vectors is linearly dependent of the other three.  Without loss of generality, assume that
$$t=au+bv+cw$$
for some $a,b,c\in\mathbb{R}$.  This means $u$, $v$, and $w$ are linearly independent.  Note that
$$t\times u=-b(u\times v)-c(u\times w)\,.$$
That is,
$$(t\times u)\times (v\times w)=-b(u\times  v)\times (v\times w)-c(u\times w)\times (v\times w)\,.$$
Now,
$$(u\times v)\times (v\times w)=\big((u\times v)\cdot w\big)\,v-\big((u\times v)\cdot v\big)\,w=\rho\,v\,,$$
where $\rho:=(u\times v)\cdot w$.  Similarly,
$$(u\times w)\times(v\times w)=\big((u\times w)\cdot w\big)\,v-\big((u\times w)\cdot v\big)\,w=\rho\,w\,.$$
Consequently,
$$(t\times u)\times (v\times w)=-b\,\rho\,v-a\,\rho\,w\,.$$
Since $u$, $v$, and $w$ are linearly independent, $\rho\neq 0$.  Thus, (*) is true if and only if $a=b=0$.  Therefore, $t=au$.  However, this contradicts the assumption that $t$ and $u$ are linearly independent.
In conclusion, we have shown that (*) is true if and only at least one of the following conditions is true:

*

*$t$ and $u$ are linearly dependent,

*$v$ and $w$ are linearly dependent, and

*the span of $t$ and $u$ is the same as the span of $v$ and $w$.

A: So, your example relies on some notion that vectors have three things:

*

*a magnitude (also called a norm or length),

*a direction, and

*a location.

Unfortunately, vectors conventionally only have the first two. That is, the vector from $[0, 0, 0]$ to $[0, 0, 1]$ is held to be the exact same vector as the vector from $[1, 1, 1]$ to $[1, 1, 2]$ even though they are in different places.
That's not to say that the location of the vector is never important: a good example is in calculating a torque where you need to know two vectors, first a force vector for the force involved, and second a displacement vector from some prespecified point of rotation about which we are calculating to the place where the force is applied. So when it is important, we generally include that as a second vector.
In this case it's not 100% clear what exactly is intended, but I think it is perhaps likely the question I would restate as this:

Points $T,U,V,W$ in $\mathbb R^3$ have displacement vectors from the origin $\mathbf t,\mathbf u,\mathbf v, \mathbf w$ respectively, such that $(\mathbf t \times \mathbf u)\times (\mathbf v \times \mathbf w) = \mathbf 0.$ Are the points $T,U,V,W$ co-planar? (And, if so, does this plane include the origin $O$?)

In this case I think the question is perhaps a sort of trick question—something that requires more insight than at first glance? So if the vectors are nondegenerate then you have a plane defined by $OTU$ with normal $\mathbf n_{TU}$ and a plane defined by $OVW$ with normal $\mathbf n_{VW}$ and the zero cross product between these two normals should suffice to make those two vectors parallel which should make the two planes equal: thinking geometrically, this makes a lot of sense.
But for instance if you were to consider a tetrahedron,
$$
\begin{align}
\mathbf t &= \begin{bmatrix}1\\ 0\\ 0\end{bmatrix}&
\mathbf u &= \begin{bmatrix}2\\ 0\\ 0\end{bmatrix}\\
\mathbf v &= \begin{bmatrix}3/2\\\sqrt{\frac12}\\+\frac12\end{bmatrix}&
\mathbf w &= \begin{bmatrix}3/2\\\sqrt{\frac12}\\-\frac12\end{bmatrix},
\end{align}
$$
then obviously $TUVW$ are not coplanar as we are talking about a tetrahedron, but also obviously the cross product requested is trivially zero as $\mathbf t \times \mathbf u = \mathbf 0.$
I am only telling you this because it's also possible that this is not a trick question and your teacher came up with the plausible intuitive argument and you have the opportunity to give a devastating rebuttal, heh.


text:
Q: Java LibGDX Moving to Touch Position on Android I'm using this code but somethings aren't perfect. It's working but not smooth. First it goes touchX and then goes touchY. But I want this at the same time. I tried different codes but didn't work. How can I fix it? What's the problem?
package com.anil.game1;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;
public class Game1 extends ApplicationAdapter {
    private SpriteBatch batch;
    private OrthographicCamera camera;
    private Texture player1Texture;
    private Rectangle player1Rectangle;
    private Vector3 touchPos;
    @Override
    public void create () {
        batch = new SpriteBatch();
        camera = new OrthographicCamera(480, 800);
        player1Texture = new Texture("Player1.png");
        player1Rectangle = new Rectangle();
        player1Rectangle.set(240, 0, 64, 64);
        touchPos = new Vector3();
    }
    @Override
    public void render () {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        if (Gdx.input.isTouched()) {
            touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
            camera.unproject(touchPos);
            //player1Rectangle.setPosition(new Vector2(touchPos.x, touchPos.y));
        }
        if (touchPos.x > player1Rectangle.x)
            player1Rectangle.x += 5;
        else
            player1Rectangle.x -= 5;
        if (touchPos.y > player1Rectangle.y)
            player1Rectangle.y += 5;
        else
            player1Rectangle.y -= 5;
        batch.draw(player1Texture, player1Rectangle.x - 32, player1Rectangle.y - 32);
        batch.end();
    }
    @Override
    public void dispose () {
        batch.dispose();
        player1Texture.dispose();
    }
}

A: In this section:
    if (touchPos.x > player1Rectangle.x)
        player1Rectangle.x += 5;
    else
        player1Rectangle.x -= 5;
    if (touchPos.y > player1Rectangle.y)
        player1Rectangle.y += 5;
    else
        player1Rectangle.y -= 5;

You are forcing the rectangle to always move in the X and Y directions by a set amount. It's never allowed to just sit still or slow down. Also, you probably don't want to be handling X and Y separately, because then its speed will be slower in the cardinal directions and faster in the diagonal directions, which would look weird. And finally, you need to work with speed and time to keep a stable movement speed.
So first of all, define a speed for your object. Also, you're going to want a Vector2 handy for calculations.
private static final float SPEED = 300f; //world units per second
private final Vector2 tmp = new Vector2();

Now after you have calculated touch position, you want to figure out what direction to move in, and how far to move along that direction. So right after your isTouched block:
//how far the player can move this frame (distance = speed * time):
float maxDistance = SPEED * Gdx.graphics.getDeltaTime();

//a vector from the player to the touch point:
tmp.set(touchPos.x, touchPos.y).sub(player1Rectangle.x, player1Rectangle.y);

if (tmp.len() <= maxDistance) {// close enough to just set the player at the target
    player1Rectangle.x = touchPos.x;
    player1Rectangle.y = touchPos.y;
} else { // need to move along the vector toward the target
    tmp.nor().scl(maxDistance); //reduce vector length to the distance traveled this frame
    player1Rectangle.x += tmp.x; //move rectangle by the vector length
    player1Rectangle.y += tmp.y;
}


text:
Q: What's the ideal way to include dictionaries (gazetteer) in spaCy to improve NER? I'm currently working on replacing a system based on nltk entity extraction combined with regexp matching where I have several named entity dictionaries. The dictionary entities are both of common type (PERSON (employees) etc.) as well as custom types (e.g. SKILL). I want to use the pre-trained spaCy model and include my dictionaries somehow, to increase the NER accuracy. Here are my thoughts on possible methods:

*

*Use spaCy's Matcher API, iterate through the dictionary and add each phrase with a callback to add the entity?

*I've just found spacy-lookup, which seems like an easy way to provide long lists of words/phrases to match.

*But what if I want to have fuzzy matching? Is there a way to add directly to the Vocab and thus have some fuzzy matching through Bloom filter / n-gram word vectors, or is there some extension out there that suits this need? Otherwise I guess I could copy spacy-lookup and replace the flashtext machinery with something else, e.g. Levenshtein distance.

*While playing around with spaCy I did try just training the NER directly with a single word from the dictionary (without any sentence context), and this did "work". But I would, of course, have to take much care to keep the model from forgetting everything.
Any help appreciated, I feel like this must be a pretty common requirement and would love to hear what's working best for people out there.

A: I would recommend looking at spaCy's Entity Ruler. If you convert your existing dictionary into the schema for matching, you can add rules for each of your entities and new types.
This is quite powerful because you can combine it with the existing statistical NER available in a standard spacy model to achieve some of the "fuzzy matching" you mention. From the docs:

The entity ruler is designed to integrate with spaCy's existing statistical models and enhance the named entity recognizer. If it's added before the "ner" component, the entity recognizer will respect the existing entity spans and adjust its predictions around it. This can significantly improve accuracy in some cases. If it's added after the "ner" component, the entity ruler will only add spans to the doc.ents if they don't overlap with existing entities predicted by the model. To overwrite overlapping entities, you can set overwrite_ents=True on initialization.

A: I use the Matcher with dynamically generated callbacks. I think it works well.
I got curious why the Matcher doesn't support fuzzy matching, and found this comment by the author of spacy on a closed issue.

You really want to precompute the search sets, rather than do them on-the-fly in the matcher. Once you've precomputed the similarity values, you can use extension attributes and a >= comparison in the Matcher to perform the search.
  I think this is a case where the implementation details strongly matter, and an API that obscures them would actually be a disservice.

I think this is a good point, and it tells you how to build what you want.


text:
Q: rapidly decaying sequence and fourier series coefficients of a compactly supported smooth function In this question the term rapidly decaying sequence is used. What is the definition of a rapidly decaying sequence.(in cases of terms being purely real or complex.) How to prove that the sequence of Fourier series coefficients of a compactly supported, real valued, smooth function is rapidly decaying ? Please suggest a reference if the proof is lengthy. Also for the converse statement.

A: A sequence of complex numbers $\{a_n\}$ is said to be rapidly decaying if it converges to $0$ at a faster rate than any negative power of $n$:
$$
\sup_n|a_n|n^k<\infty\qquad\forall k\in\mathbb{N}.
$$
Let $\mathbb{T}$ denote the unit circle. If $f\in C^\infty(\mathbb{T})$, that is, $f$ is a periodic function of period $2\pi$ that admits derivatives of all orders, then the (doubly infinte) sequence of its Fourier coefficients is rapidly decaying. Indeed, integration by parts shows that $|\hat f_n|\le n^{-1}\|f'\|_\infty$; iterating the argument one gets that for all $k\in\mathbb{N}$, $|\hat f_n|\le n^{-k}\|f^{(k)}\|_\infty$.
Conversely, if the sequence of Fourier coefficients of a function $f\in L^1(\mathbb{T})$ is rapidly decaying, then the corresponding Fourier series and all the series derived from it by term by term differentiation are uniformly convergent. It follows that $f$ is equal almost everywhwre to a $C^\infty$ function.
Faster decay gives more smoothnes of $f$. See for instance Section 2 of chapter V in AN INTRODUCTION TO HARMONIC ANALYSIS by Yitzhak Katznelson.


text:
Q: C++ final class and slicing idiom I happened to be browsing the source for mongoDB, and found this interesting construct:
class NonspecificAssertionException final : public AssertionException {
public:
    using AssertionException::AssertionException;

private:
    void defineOnlyInFinalSubclassToPreventSlicing() final {}
};

How does the private method prevent slicing? I can't seem to think of the problem case.
Cheers, George

A: The only member functions to which the final specifier may be applied are virtual member functions. It is likely that in AssertionException or one of it's own base classes, this member is defined as
virtual void defineOnlyInFinalSubclassToPreventSlicing() = 0;

Thus, all classes in the hierarchy save the most derived ones are abstract base classes. One may not create values of abstract classes (they can only serve as bases). And so, one may not accidentally write
try {
    foo();
}
catch(AssertionException const e) { // oops catching by value
}

If AssertionException was not abstract, the above could be written. But when it's abstract the compiler will complain at that exception handler, forcing us to catch by reference. And catching by reference is recommended practice.
Marking the member (and class) as final ensures no further derivation is possible. So the problem cannot reappear accidentally when the inheritance hierarchy is changed. Because a programmer that adds another class and again defines defineOnlyInFinalSubclassToPreventSlicing as final will elicit an error from the compiler, on account of this member already being declared final in the base. They will therefore have to remove the implementation from the base class, thus making it abstract again.
It's a bookkeeping system.


text:
Q: MS SQL Server 2000 - check for existing database error I use MS SQL Server 2000 SP4 and I have this part of script, that checks for existing database:
IF EXISTS (SELECT * FROM sysdatabases WHERE name='MY_DBNAME')
BEGIN
    PRINT 'Using the existing database MY_DBNAME.'
    USE MY_DBNAME
END
ELSE
BEGIN
    PRINT 'Creating new database MY_DBNAME.'
    CREATE DATABASE MY_DBNAME
END
GO

I keep getting this error:
Could not locate entry in sysdatabases for database 'MY_DBNAME'. No entry found with that name. Make sure that the name is entered correctly.
Is there a way to disable this message, or is there another way for checking, if a table exists?

A: It's trying to compile the whole thing, including "USE MY_DBNAME" before it runs. Compilation fails because this database doesn't exist. You can't, I'm afraid, do what you're trying to do in a single SQL batch.

A: Thanks to your hints I've found the solution:
IF EXISTS (SELECT * FROM sysdatabases WHERE name='MY_DBNAME')
BEGIN
    PRINT 'Using the existing database MY_DBNAME.'
END
ELSE
BEGIN
    PRINT 'Creating new database MY_DBNAME.'
    CREATE DATABASE [MY_DBNAME]
END
GO

USE [MY_DBNAME]
GO