text:
Q: Android memory leaks Link.
Now I have a context leak in my project and on the link it pretty much explains everything that could cause it.
To be honest I tried to remove as much as possible that has context variables but I am having a problem with my Grid View and my base adapter and I really need help I have been pounding my head over this. Sometimes it elude me that it got garbage collected then shows itself like a ninja on the other classes.
My question: "What would you guys suggest that I should change?" and "What should I watch out for?"
Here is what I did:
1. Created a Hash map for my drawable images
2. Created a Base Adapter for the gridview
3. My code for the loadCover class
private static Map ImageLocator = Collections.synchronizedMap(new WeakHashMap());
private class BaseA extends BaseAdapter{
    private LayoutInflater inflater;

    public BaseA(Context context){
        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View row = convertView;
        viewHolder vh = new viewHolder();

        row = inflater.inflate(R.layout.book_row_view, null);
        vh.authors = (TextView)row.findViewById(R.id.book_Author);
        vh.image = (ImageView)row.findViewById(R.id.icon);
        vh.date = (TextView)row.findViewById(R.id.Date);
        vh.Titles = (TextView)row.findViewById(R.id.Book_Title);
        vh.fileName = (TextView)row.findViewById(R.id.FileLocation);

        try{
            String temp = File_Name.get(position);
            vh.fileName.setText(temp);
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        Book_Information bi;
        bi = new Book_Information();
        bi = dbh.getData(File_Name.get(position));
        //Gets the right book information for all the items
        new LoadCover(vh.image, bi).run();
        if(bi.getBook_Author() != null || bi.getBook_Date() !=null || bi.getBook_Description() != null ||
                bi.getBook_Title() != null){

            vh.authors.setText(bi.getBook_Author());
            vh.date.setText(bi.getBook_Date());
            vh.Titles.setText(bi.getBook_Title());
        }
        return row;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return File_Name.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

}

private class LoadCover implements Runnable{
    ImageView image; Book_Information bi;

    public LoadCover(ImageView image, Book_Information bi){
        this.image = image;
        this.bi = bi;
    }

    public void run() {
        // TODO Auto-generated method stub
        Drawable draw = ImageLocator.get(bi.getBook_File_Name());

        if(draw!=null){
            image.setImageDrawable(draw);
        }else{
            new UpdateImages(image, bi).run();
        }
        draw = null;
    }

}

private class UpdateImages implements Runnable{
    ImageView image;
    Book_Information book_info;

    public UpdateImages(ImageView imageView,  Book_Information bookInfo){
        this.image = imageView;
        this.book_info = bookInfo;
    }
    public void run(){
        try{
            Bitmap bm = getBitmap(book_info);
            FastBitmapDrawable fbd = new FastBitmapDrawable(bm);
            image.setImageDrawable(fbd);
            ImageLocator.put(book_info.getBook_File_Name(), fbd);
            bm = null;
        }catch (OutOfMemoryError e) {
            // TODO: handle exception
            ImageLocator.clear();
        }
    }
}

A: I've looked at your code and refactored it into a more manageable manner, it has pointed out a few things.
Your doing some type of image loading in your getView method, this takes too long and should be done in an ASyncTask, or a handler with some type of callback.
You then store these bitmaps in a static map that will stay in memory for the lifetime of your app, this is baaad and keeps references to your context when you create the bitmaps. I can see your using it as a kind of image cache for when they are loaded, maybe think of a different way if this is causing you out of memory errors.
Here is your code, refactored:
/**
 * @author paul.blundell
 *         May 15, 2012
 */
public class MyAct extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        List<String> fileNames = new ArrayList<String>(); // Whatever filenames you get
        List<BookInformation> list = dbh.getData(fileNames); // However you get your data from the database (usually in a Service)

        BaseA base = new BaseA(inflater, list);

        // Do whatever with base
    }
 }

The adapter class:
    public class BaseA extends BaseAdapter {

        // Having a static map means it lives the entire life of your application, your drawables should take a context
        // when they are being created therefore they have a reference to your Activity, and this is not being destroyed
        public static Map<String, Drawable> imageLocator = new WeakHashMap<String, Drawable>();

        private LayoutInflater inflater;
        private List<BookInformation> books;

        public BaseA(LayoutInflater inflater, List<BookInformation> books) {
            this.inflater = inflater;
            this.books = books;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View rowView = convertView;
            ViewHolder vh = null;

            if(rowView == null){
                // Get new instance of our row view
                rowView = inflateView();
                // Hold the view in an object so it doesnt need to be re-fetched
                vh = new ViewHolder();

                vh.authors  = (TextView)  rowView.findViewById(R.id.book_author);
                vh.image    = (ImageView) rowView.findViewById(R.id.book_icon);
                vh.date     = (TextView)  rowView.findViewById(R.id.book_date);
                vh.titles   = (TextView)  rowView.findViewById(R.id.book_title);
                vh.fileName = (TextView)  rowView.findViewById(R.id.file_location);

                // Cache the view so it can be re-accessed later
                rowView.setTag(vh);
            } else {
                vh = (ViewHolder) rowView.getTag();
            }

            BookInformation book = books.get(position);
            vh.fileName.setText(book.getFileName());

            // Gets the right book information for all the items
            loadCover(vh.image, book.getFileName());

            if (book.getAuthor() != null){
                vh.authors.setText(book.getAuthor());
            }
            if(book.getDate() != null){
                vh.date.setText(book.getDate());
            }
            if(book.getTitle() != null){
                vh.titles.setText(book.getTitle());
            }

            return rowView;
        }

        private View inflateView() {
            return inflater.inflate(R.layout.view_book_row, null);
        }

        public int getCount() {
            return books.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        private void loadCover(ImageView image, String filename) {
            Drawable draw = imageLocator.get(filename);

            if (draw == null) {
                draw = updateImage(filename);
            }
            imageLocator.put(filename, draw); // This is your problem keeping a reference to these drawables in a static map
            image.setImageDrawable(draw);
        }

        private Drawable updateImage(String filename) {
            Bitmap bm = getBitmap(filename);
            Drawable drawable = new BitmapDrawable(bm);
            return drawable;
        }

        private Bitmap getBitmap(String filename) {
            return null; // I don't know how you get a bitmap but you shouldn't do this in getView() , use a callback
        }

       private static class ViewHolder {
            public TextView fileName;
            public TextView titles;
            public TextView date;
            public ImageView image;
            public TextView authors;
        }
    }

Separate domain class bookInformation:
public class BookInformation {

        public String getFileName() {
            return "filename";
        }

        public String getTitle() {
            return "title";
        }

        public String getDate() {
            return "date";
        }

        public String getAuthor() {
            return "author";
        }
    }


text:
Q: I need help understanding java.lang.StringIndexOutOfBoundsException I wrote code for caesar cipher but it's not working... Please help me solve this.
import java.io.IOException;
import java.util.Scanner;

public class test1 {

    public static void main(String[] args) throws IOException {
        System.out.println("enter the String");
        StringBuffer str = new StringBuffer(new Scanner(System.in).nextLine());
        System.out.println("encrypting the String . . ." +str);

        for(int j=0; j<str.length(); j++){
            for(int i=0; i<256; i++) {
                if((char)i == str.charAt(j)){
                    str.setCharAt(j, (char)(i+3));
                }
            }
        }
        System.out.println("encrypted String . . .");
    }
}

Here your solution works and no more java.lang.StringIndexOutOfBoundsException
now there is another problem occured . . . .
I tried different inputs but all the time it replies same answer: ??????

A: Strings in java are zero based. So you have to remove the = in your first loop:
for(int j=0; j<str.length(); j++){

A: use  for(int j=0; j<str.length(); j++) // string index length are 0 based
instead of
for(int j=0; j<=str.length(); j++)

A: String's character always start with index 0, it means if you store
String str="text";

then
str.charAt(0) // return "t"
str.charAt(1) // return "e"
str.charAt(2) // return "x"
str.charAt(3) // return "t"

and if you call str.charAt(4)

it will throw java.lang.StringIndexOutOfBoundsException it means, the
  index which you are targeting to get data from is out of bound.

So just change your for loop as everybody suggested.
Like this,
        for(int j=0; j<str.length(); j++){
            for(int i=0; i<256; i++) {
                if((char)i == str.charAt(j)){
                    str.setCharAt(j, (char)(i+3));
                }
            }
        }

A: Use j<= str.length()  to j< str.length() in the for(int j=0; j<str.length(); j++) as index starts from 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to check two images on imageview are overlapping to eachother I am creating an application.I am overlapping two image on each other. My image is bigger than screen so imageView is adjusting it .I want to know that  images are overlapping each other  or not ...if they are not overlapping then how should i do that they overlap to each other....
this is image now    image now i want to overlap this image but i want to make sure tht this image should be overlap to each other properly ........


text:
Q: Checkbox Check All unable to detect data I'm having issues with retrieving details when checking the checkbox that ticks all the boxes. It works when i UNCHECK when it should be working when i CHECK.
When i Check it, i get Zero( by right should take sum of checked box data)
When i UNcheck, i get Sum of all checked box data( by right should get zero)
I cant seem to "flip it" around or realise the logic here. Any advice would be greatly appreciated.
$(function() {
    var totalPrice = 0.00,
        totalWeight = 0.00,
        shippingFee = 0.00,
        totalCost = 0.00,
        agentFee = 0.00;

    updateTotals = function() {
        totalPrice = 0.00;
        totalWeight = 0.00;
        shippingFee = 0.00;
        totalCost = 0.00;
        agentFee = 0.00;

        $('#arrange-delivery-table tbody input[type=checkbox]:checked').each(function(i, e){
            totalWeight += Number($(this).data('weight'));
            totalCost += Number($(this).data('cost'));
        });
    };

    $('#arrange-delivery-table :checkbox').change(function(e){
        updateTotals();
    });
});

A: Try using click event:
$('#arrange-delivery-table :checkbox').click(function(e){
    updateTotals();
});


text:
Q: tab close event Anyone know of a way to catch a Google Chrome Tab close event? (I see there is an extension API for this but I am wondering if there such an API for Web apps; can't find it)

A: You can use window.onunload or window.onbeforeunload and if you are using jQuery you can use $(window).unload. these method get called even when you refresh the page, and you can not differentiate between unload and refresh of tab.
 following are implementations
window.onunload = function(){
 //your code
};

or
 window.onbeforeunload =function(){
 //your code
};

$(window).unload( function(){
 //your code
}; );

A: You can use it for close the actual tab selected.
window.close()

And you can change this function.


text:
Q: Using both OOP and Function programming paradims I read about OOP and Function programming. And I found both have pros and cons.
Such as:

*

*OOP: have side effect, and sometimes it is very usefull

*Function: easy to code and think. But don't have side effect and loop.

And I wonder if I can using both OOP and Function paradigm in one project. Is it be recommended in practice?

A: There's nothing preventing both paradigms from being used together. Arguments on each side sometimes can be misleading as people tend to focus on languages and their features as opposed to the paradigms themselves. OOP doesn't need to have state/side effects, and functional programming doesn't always make things easier or faster. The good engineer will use the right tools for the right task, which means getting a good understanding of both.


text:
Q: What does the "force resume" feature of BitTorrent clients actually do? In every BitTorrent client I've ever used, there are two features: "resume" and "force resume". If "resume" doesn't work, one can "force resume", which often actually works. As if you are digitally "kicking" the torrent with your foot to make it start/continue from being stalled/stuck.
This is satisfying when it works, but what exactly does it do? And if it can do this, why doesn't the normal "resume" feature do whatever the "force resume" one does? Or even automatically, without any requirement for the user to be there and manually intervene?

A: The difference between the two options depends on your seeding rules.
A typical example might be
"up to 8 torrents total active with up to three of those being downloads".
So if you have a large number of torrents, not all of them will be active
when the limit specified by the rule is exceeded.
Inactive torrents may have their status indicated as "Queued".
The torrents that are inactive will wait for an active torrent
to terminate so they can start.
The "force resume" command will force an inactive torrent to become active,
so exceeding the limit.
The command "resume" is for use when some torrent(s) is suspended
manually by yourself. These torrents stay inactive until you use the
"resume" command. Then they can wait for an active slot to become available,
so if the limit was not exceeded they will start working immediately.
Even when active, a torrent may not do much if it's searching for
sources on the internet, or if it is waiting for some source(s) to
agree to the connection.

A: What exactly does Force Resume do?
In qBittorrent:

It keeps the connection open between peers/seeders (and the tracker), so you can (almost) instantly resume downloading. Stop closes your connection between you, any peers/seeders, and the tracker.

Source: Question: Can Qbittorrent Upload Files From Computer - SovereignValley
Other clients may also have this option (Deluge doesn't)


text:
Q: listener port and serving port in server I am planing to write one customized http server in java. I thought of using one listener port which will always listen for incoming calls. Whenever incoming call will come, it will accept and pass the socket object in another thread. So that thread will be responsible for serving response. When response is completed, it will be closed. But now the problem I think is that if too much request comes at a time then no more port would be available. So I am thinking of having some fixed number of serving port and reuse those for sending response back. Can anyone suggest how can i do that in java?

A: You don't really want to limit ports as much as you want to limit threads, that's why many servers use a threadpool that contains way less threads than the amount of available ports.


text:
Q: Do something in hover if the right button of the mouse is down (pressed) I need to zoom an image when mouse is over the image and the right button of the mouse is kept pressed. something like:
$('img').hover(
     function(){
       if (the-right-mouse-button-is-pressed){
         $(this).animate({
         width:  $(this).width() *2,
         height: $(this).height()*2,
         }, 500);
       }
     },
});

I need help. Thanks.

A: Edit: For your below comment,

Thanks. However, it requires a right-click on the picture. it does not
  work if you keep the right button down somewhere else in the screen
  and then pass the image

You need to add mouseup event and zoom conditionally. See below code, DEMO
var hasExpanded = false;
$('img').on('mousedown mouseup', function(e) {
    if (e.which == 3) {
            if (!hasExpanded) {
            $(this).animate({
                width: $(this).width() * 2,
                height: $(this).height() * 2,
            }, 500);
        }
        hasExpanded = true;
    }
}).mouseleave(function(e) {
    if (hasExpanded  == true) {
    $(this).animate({
        width: $(this).width() / 2,
        height: $(this).height() / 2,
    }, 500);
    hasExpanded = false;
}
});

What you need cannot be achieved through hover. Hover will be triggered on mouseeneter which will be called only once and It cannot record the mousedown event which happens at later point.
You need to implement mousedown handler. See below,
DEMO - Demo has both mousedown and mouseleave implemented.
$('img').mousedown(function(e) {
    if (e.which == 3) {
        $(this).animate({
            width: $(this).width() * 2,
            height: $(this).height() * 2,
        }, 500);
    }
});


text:
Q: Complex number exponential form negative i What does negative i mean in exponential form of a complex number?

Is it equal to $5e^{i6\pi/5}$ ?

A: Exponential complex representation just implies that that complex number you have has a circular-like figure in the complex plane.
If you simply wanna solve it, then you take -24π/5 to 6π/5 due to the repetition of the waves and get the result.
An interesting way to look at this, and this is just as I see it, would be that as e^{ix} give the curve with vector pointing outwards of the origin so it's conjugate must have the vector pointing toward the origin. But that just increases complexity in complex. So you better not dive into it.
Hope this helps!!


text:
Q: Encryption, loop device and journaling file system on Linux I've been reading up on tools like Truecrypt, loop-AES and Cryptoloop that use a "loop device" to create an encrypted disk volume within a file.
On the README page for loop-AES, it has this paragraph about journaling file systems:
http://loop-aes.sourceforge.net/loop-AES.README

Don't use a journaling file system on
  top of file backed loop device. Device
  backed loop device can be used with
  journaling file systems as device
  backed loops guarantee that writes
  reach disk platters in order required
  by journaling file system (write
  caching must be disabled on the disk
  drive, of course). With file backed
  loop devices, correct write ordering
  may extend only to page cache (which
  resides in RAM) of underlying file
  system. VM can write such pages to
  disk in any order it wishes, and thus
  break write order expectation of
  journaling file system.

Do you know what they mean by "on top of file backed loop device"?  Are they referring to a situation where my disk is physically formatted with a journaling file system (like ext3, ext4, or XFS) and then within that file system I create a file which houses the virtual disk volume?  Or are they describing the reverse, where the journaling file system is within the file that houses the virtual disk volume?
I have my Linux partitions formatted as ext4, so if they're referring to the first situation, I would have to resize partitions and create an ext2 or FAT partition to save the file that will house the Truecrypt/loop-AES/Cryptoloop volume.

A: A "file backed loop device" is a loop-mounted disk file.
Such as mounting /home/mike/mydisk.raw on /mnt.
Device backed is when you've mounted something from /dev, like /dev/sda3
The situation they are referring to has the following structure:
Files
  |
  v
Journaled Filesystem
  |
  v
Encrypted loop mount
  |
  v
Disk file
  |
  v
Journaled Filesystem
  |
  v
Physical device

As you can see there are two filesystems in the chain with two lots of caching and two lots of journaling.  Not only wasteful but can cause problems with write-ordering.  So just don't use journaling on the top-level filesystem.  It's simple enough to turn off.
The situation they say I OK has the following structure:
Files
  |
  v
Journaled Filesystem
  |
  v
Encrypted loop mount
  |
  v
Physical disk

You see there is only one filesystem (and only one set of journaling and caching) in that arrangement.


text:
Q: Error while running Tensorflow on SQL Server (ImportError: DLL load failed: The paging file is too small for this operation to complete.) I am faced with this error while running Tensorflow on SQL Server.
It seems like it is some memory issue.
Any advice?
Main Error: ImportError: DLL load failed: The paging file is too small for this operation to complete.
Msg 39004, Level 16, State 20, Line 1
A 'Python' script error occurred during execution of 'sp_execute_external_script' with HRESULT 0x80004004.
Msg 39019, Level 16, State 2, Line 1
An external script error occurred:

Error in execution.  Check the output for more information.
C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS2017\PYTHON_SERVICES\lib\site-packages\h5py\__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS2017\PYTHON_SERVICES\lib\site-packages\tensorflow_core\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS2017\PYTHON_SERVICES\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()

Msg 39019, Level 16, State 2, Line 1
An external script error occurred:
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS2017\PYTHON_SERVICES\lib\site-packages\tensorflow_core\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS2017\PYTHON_SERVICES\lib\imp.py", line 242, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS2017\PYTHON_SERVICES\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The paging file is too small for this operation to complete


text:
Q: Compute $\pi_2(S^2 \vee S^2)$ As far as I know, there are two ways to calculate higher homotopy groups. One way is if we have a fibration then we get a long exact sequence in homotopy. The other is if we know a space is $(n-1)$-connected, then by Hurewicz Theorem, $\pi_n \cong H_n$.
I know $H_2(S^2 \vee S^2)=\mathbb{Z} \oplus \mathbb{Z}$ and $\pi_1(S^2 \vee S^2)$ is trivial as the pushout of $\pi_1(S^2) \leftarrow \pi_1(\ast) \rightarrow \pi_1(S^2)$ (using van Kampen's Theorem).
Is it true that a wedge of $n$-spheres is $(n-1)$-connected? If so, why? If this is the case, Hurewicz applies.
Also, is there any fibration involving $S^2 \vee  S^2$? I thought about the Hopf fibration $S^1 \rightarrow S^3 \rightarrow S^2$, but intuitively I doubt that this produces another fibration $S^1 \vee S^1 \rightarrow S^3 \vee S^3 \rightarrow S^2 \vee S^2$.
Any help you can provide would be appreciated!

A: I think the question meant to ask about $\pi_2(S^2 \vee S^2)$. Since $\pi_0$ and $\pi_1$ vanish, the Hurewicz map gives an isomorphism $\pi_2(S^2 \vee S^2) \to H_2(S^2 \vee S^2) = \mathbb{Z}^2.$

A: Any wedge of $n$-spheres is indeed $(n-1)$-connected. One way to see this is to give $\vee_{i=1}^kS^n$ a CW structure with one $0$-cell and $k$ $n$-cells. If $f\colon S^i\to \vee_{i=1}^kS^n$ is any pointed map then by cellular approximation $f$ is pointed-homotopic to a cellular map $\tilde{f}$, and if $i < n$ then $\tilde{f}$ must be constant.


text:
Q: ¿Cuántas posiciones ocupa una variable COMP en un fichero secuencial? - COBOL Alguien sabría decirme cuántas posiciones ocuparían las siguientes variables en un fichero secuencial:
02  VAR1     PIC 9(5) COMP.
02  VAR2     PIC 9(6) COMP.

Gracias. Un saludo.

A: Según este link que describe el formato Binary o Comp de COBOL, depende de la plataforma, puediento ocupar 3 (IBM) o 4 (Micro Focus) bytes.
Como nota al margen, también tené en cuenta que al persistir el dato en un fichero, y también dependiendo de la plataforma, puede estar con los bytes más pesados al inicio o al final (Big Endian vs Little Endian).


text:
Q: Combo Charts in Google Sites using Google Sites Is there a way to create Combo charts using apps script? I need to create a chart using google sites, but I havent found the way.
Many thanks in advance.

A: While there are many types of charts possible via Apps Script (documentation here and a tutorial here), its not possible to create combo charts today.
There is already an open request to support this. You can follow that enhancement request for more info.


text:
Q: How can I convert a number to text in the excel "datatables.js" download I'm trying to convert a number as text in datatables.js while downloading excel file. If I normally put a single quote ' manually in the excel file before a number it works.. but when I do that programmatically it doesn't.. where I'm doing wrong? The following are my columns declaration;
"columns": [
{ "data": "ID", "visible": false, "searchable": false },
{
    "data": "ProductCode", "title": 'Product Code', "visible": true, responsivePriority: 1, render: function (data, type, row) {

        if (type === 'export') {

            return "'" + data;
        }
        else {

            return data;
        }
    }
},
...
]

This is my button declaration;
// Initialize Download Button
new $.fn.dataTable.Buttons(table, {

    buttons: [{
        extend: 'excel', text: 'Download Excel', className: 'btn-sm btn-success downloadButton', exportOptions: {
            columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
            orthogonal: 'export'
        }
    }]
});

It shows like this '12345 in the downloaded excel file but if I just press F2 (Edit) and press enter excel converts it to the text :(. Any help will be highly appreciable.

A: Have you tried removing the single quote?
Just do this return "" + data;. It should work.

A: I solved this issue by commenting out below code in addrow function in datatable.js file.
// Detect numbers - don't match numbers with leading zeros or a negative
// anywhere but the start
                //if ( typeof row[i] === 'number' || (
                //      row[i].match &&
                //      $.trim(row[i]).match(/^-?\d+(\.\d+)?$/) &&
                //      ! $.trim(row[i]).match(/^0\d+/) )
                //) {
                //  cell = _createNode( rels, 'c', {
                //      attr: {
                //          t: 'n',
                //          r: cellId
                //      },
                //      children: [
                //          _createNode( rels, 'v', { text: row[i] } )
                //      ]
                //  } );
                //}
                //else {

below is the function
 var addRow = function ( row ) {
            currentRow = rowPos+1;
            rowNode = _createNode( rels, "row", { attr: {r:currentRow} } );

            for ( var i=0, ien=row.length ; i<ien ; i++ ) {
                // Concat both the Cell Columns as a letter and the Row of the cell.
                var cellId = createCellPos(i) + '' + currentRow;
                var cell;

                if ( row[i] === null || row[i] === undefined ) {
                    row[i] = '';
                }

                // Detect numbers - don't match numbers with leading zeros or a negative
                // anywhere but the start
                //if ( typeof row[i] === 'number' || (
                //      row[i].match &&
                //      $.trim(row[i]).match(/^-?\d+(\.\d+)?$/) &&
                //      ! $.trim(row[i]).match(/^0\d+/) )
                //) {
                //  cell = _createNode( rels, 'c', {
                //      attr: {
                //          t: 'n',
                //          r: cellId
                //      },
                //      children: [
                //          _createNode( rels, 'v', { text: row[i] } )
                //      ]
                //  } );
                //}
                //else {
                    // Replace non standard characters for text output
                    var text = ! row[i].replace ?
                        row[i] :
                        row[i].replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, '');

                    cell = _createNode( rels, 'c', {
                        attr: {
                            t: 'inlineStr',
                            r: cellId
                        },
                        children:{
                            row: _createNode( rels, 'is', {
                                children: {
                                    row: _createNode( rels, 't', {
                                        text: text
                                    } )
                                }
                            } )
                        }
                    } );
                //}

                rowNode.appendChild( cell );
            }
            relsGet.appendChild(rowNode);
            rowPos++;
        };


text:
Q: JavaScript variable to php session variable so I got this really simple jQuery datatable, and i'm trying to get my selected value into a php variable. Here is my code:
<script>
        var hlr = 0;   // Reference to the currently highlighted row

function rowClick()
{
   if (hlr)
      $("td:first", hlr).parent().children().each(function(){$(this).removeClass('markrow');});
   hlr = this;
   $("td:first", this).parent().children().each(function(){$(this).addClass('markrow');});

   // You can pull the values out of the row here if required
   var a = $("td:first", this).text();
   var b = $("td:eq(1)", this).text();

    //$_SESSION['Klantnaam']="+a+");

   alert("Keuze = "+a+""); //this is what I need in my PHP session variable.
}
      </script>

Thanks for reading, a response is highle appreciated.

A: I had already faced this question on my recent project
Here is my solution to you
But i had to take value in to session variable so
STEPS:

*

*Created a php file which puts value to session variable

*Send a ajax request to that php file with js var value


text:
Q: Throw custom error during JSON deserialization I have the following POJO:
@Entity // This tells Hibernate to make a table out of this class
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

    private String username;

    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) throws DataFormatException {
        if(name.equals(""))
        {
            throw new DataFormatException("Mpla Mpla");
        }
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {

        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @JsonCreator
    public User(@JsonProperty("name") String name, @JsonProperty("email") String email,@JsonProperty("username") String username,@JsonProperty("password") String password) throws DataFormatException {
        setName(name);
        this.email = email;
        this.username = username;
        this.password = password;
}
    }

And the following controller:
public class MainController {
    @Autowired // This means to get the bean called userRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;
    }
    @PostMapping(path="/add") // Map ONLY POST Requests
    public @ResponseBody String addNewUser (@RequestBody @Valid User user1) {
        // @ResponseBody means the returned String is the response, not a view name

        userRepository.save(user1);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }

The problem is that instead of producing the error DataFormatException it produces:
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
    "message": "JSON parse error: Can not construct instance of hello.Users.User, problem: Mpla Mpla; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of hello.Users.User, problem: Mpla Mpla\n at [Source: java.io.PushbackInputStream@7604dc21; line: 6, column: 1]",

Although as can be seen above the problem is correct but the message is wrong. So what can be done in order to produce the wanted error and not the one produced by Jackson?

A: use below code in your controller.
@RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public SecurityToken register(@RequestBody @Valid SecurityUser user, BindingResult result) {
        List<ObjectError> st = result.getAllErrors();
        String errorFields = "";
        for (ObjectError error : st) {
            errorFields = errorFields + error.getDefaultMessage();
        }
        if (!errorFields.equals("")) {
            throw new CustomException(errorFields);
        }
        return service.register(user);
    }

you can use annotation for fields as :
import org.hibernate.validator.constraints.NotEmpty;

public class SecurityUser {

    @NotEmpty(message = "Email id is mandatory.")
    private String emailId;

For Exception handling you can use HandlerMethod in spring controller or ControllerAdvice.
@ControllerAdvice
public class SecurityControllerAdvice {

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public CustomResponse handleSecurityException(CustomException se) {
        CustomResponse response = new CustomResponse(se.getMessage());
        return response;
    }
}


text:
Q: Which node in a MarkLogic cluster runs the CPF Action Module? I have a MArkLogic cluster with 3 nodes:

*

*Node 1

*Node 2

*Node 3
On this clustered environemnt I have a database test which has one forest test-01.
The Primary Host for the forest test-01 is on Node 1. Also, I have CPF installed on the database test
Now, when I insert any document in the database test, the CPF action module will be executed on which Node's Task Server thread?
Will the Primary Host of the forest in which the document gets created ALWAYS executes the CPF action module?
What If I configure a failover replica of forest test-01 on Node 2 and Node 3 and after that stop the MarkLogic service on Node 01. which Node's Task Server will then execute the CPF action modules?

A: CPF uses triggers. A pre-commit trigger will fire on the same host that processes the update. This is independent of forest and cluster configuration. A post-commit trigger will run on the Task Server on the host with the affected forest (thanks to John Snelson for correcting my understanding on this point).
CPF actions use both kinds of triggers. So if you want to limit triggers to a single host, ensure that all your updates are processed on that host and ensure all the affected forests are on that same host. You'd also want to handle host failover by moving update traffic to the next host.
CPF also uses the database online event, which is a little different. I believe that can run on any host, but it may be limited to hosts with any forests attached to the database.


text:
Q: How can I copy content from one string vector to another? For example, I have a string-based vector:
vector<string> text_vec;

There are several words stored in each string. So, I need to copy the each word from this vector to another string-vector, but I should place each word in the individual string. How can I do this?

A: vector<string> text_vec_2;

for(unsigned int i=0;i<text_vec.size();++i){

     // assuming a split-function which you have created
     // which returns a vector with the individual words
    vector<string> words = splitString(text_vec[i]);

    // copy the words into the new vector
    for(unsigned int j=0;j<words.size();++j){
        text_vec_2.push_back(words[j]);
    }
}

A: You mean your vector contents look like this?
{ "word0", "word1 word2 word3", "word4 word5" }

And you want to have a result like this:
{ "word0", "word1", "word2", "word3", "word4", "word5" }

The first important thing is to define what constitutes a word. I'll assume a word is everything separated by at least one space. In practice, you may want to handle a few special cases, for example:

*

*Empty strings.

*Other whitespace characters.

*Newlines.

Let's first define a string-split function that takes a std::string and returns a std::vector<std::string>. It will first provide simple splitting using the aforementioned assumption; you can make it more sophisticated later on:
std::vector<std::string> split(std::string const& input)
{
    std::vector<std::string> result;
    std::istringstream is(input);
    std::string word;
    while (is >> word)
    {
        result.push_back(word);
    }
    return result;
}

Having this function at our disposal, we can apply it to your input vector:
std::vector<std::string> normalise(std::vector<std::string> const& strings)
{
    std::vector<std::string> result;
    for (auto const& string : strings)
    {
        auto const tokens = split(string);
        for (auto const& token : split(string))
        {
            result.push_back(token);
        }
    }
    return result;
}

Here's a complete test program:
#include <iostream>
#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> split(std::string const& input)
{
    std::vector<std::string> result;
    std::istringstream is(input);
    std::string word;
    while (is >> word)
    {
        result.push_back(word);
    }
    return result;
}

std::vector<std::string> normalise(std::vector<std::string> const& strings)
{
    std::vector<std::string> result;
    for (auto const& string : strings)
    {
        auto const tokens = split(string);
        for (auto const& token : split(string))
        {
            result.push_back(token);
        }
    }
    return result;
}

int main()
{
    std::vector<std::string> const input = { "word0", "word1 word2 word3", "word4 word5" };

    for (auto const& word : normalise(input))
    {
        std::cout << word << "\n";
    }
}


text:
Q: Angular UI Router with ng-enter-stagger I hope someone can help me I have been stuck on this for a while.
I have a simple jsfiddle here: http://jsfiddle.net/mcneela86/aodsux3p/
Which is using the ng-enter-stagger class to stagger the animations on each list item, and it seems to work fine.
I have then tried to use this method with an app built on the ui-router but the animation is not working: http://plnkr.co/edit/IDpTQuwELq0zWsqMDrPw?p=preview
Am I doing something wrong or does this method of animation not work within the ui-router?
Any help would be really appreciated.

A: In the JSFiddle AngularJS version 1.2.1 is used, while in the Plunker version 1.4.1 is used. A lot has changed between those two versions.
From the documentation:

Are animations run when the application starts?
No they are not. When an application is bootstrapped Angular will
  disable animations from running to avoid a frenzy of animations from
  being triggered as soon as the browser has rendered the screen. For
  this to work, Angular will wait for two digest cycles until enabling
  animations. From there on, any animation-triggering layout changes in
  the application will trigger animations as normal.

In this case you can use the ng-animate-children attribute.
For example:

{{ dog }}

Demo: http://plnkr.co/edit/X2DDZUuspOEWEWkADtxw?p=preview


text:
Q: I'm a newbie and having problems with a rounding here I've used the rounding in another portion of my homework, but I'm having issues with this one...
pred_weight = []

pred_weight = [(length[i]*0.6)-5.2 for i in range (0,len(weight))]

round(pred_weight,4)

print (round(int(pred_weight)))

The error it kicks out is...
TypeError                                 Traceback (most recent call last)
<ipython-input-275-9d2218701582> in <module>
      3 pred_weight = [(length[i]*0.6)-5.2 for i in range (0,len(weight))]
      4
----> 5 round(pred_weight,4)
      6 print (round(int(pred_weight)))
      7

TypeError: type list doesn't define __round__ method

I've tried setting it up as an int, but got nowhere with that.  Any suggestions?

A: That's because you're applying the round method to the list. It should be applied to individual elements in your list.
Something, like this:
pred_weight = [round(i,4) for i in pred_weight]

you can apply round here also:
pred_weight = [round(((length[i]*0.6)-5.2),4) for i in range(len(weight))]

A: try this:
pred_weight = []

pred_weight = [(length[i]*0.6)-5.2 for i in range (0,len(weight))]

for i in pred_weight:
    print (round(i,4))

A: You probably need to do something like this
round(pred_weight[0])

You're trying to round a list object, which looks something like this in theory
my_list = [0, 5.4, 10.2, 42.7, 15.3]

You can't round a list object, you have to pass a number through. So if I wanted the second index, which is 5 in this list, i would do my_list[1] to return 5.4 and then I can round that number.


text:
Q: Unable to navigate using storyboards in Xamarin iOS "PrepareForSegue(UIKit.UIStoryboardSegue, Foundation.NSObject)' is marked as an override but no suitable method found to override" is the error i am getting when i trying to write the below code
 public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
                {
                    if (segue.Identifier == "detailSegue") {

                        var dtlVC = segue.DestinationViewController as DetailVC;

![Unable to Override][2]

                }
            }

A: That class must be classed from UIViewController or UITableViewController. If it's not a view controller subclass then it will not find the super class definition for overriding and hence the error.


text:
Q: Two Spring apps each use jpa to control a single database Two Spring apps each use jpa to control a single database.
Each Spring app must use a single database.
Will spring.jpa.hibernate.ddl-auto = update work properly?

A: In my opinion, having 2 applications using directly the same database is a poor design.
Here is a quote from this sofware engineering answer

The more applications use the same database, the more likely it is
  that you hit performance bottlenecks and that you can't easily scale
  the load as desired. SQL Databases don't really scale. You can buy
  bigger machines but they do not scale well in clusters!
Maintenance and development costs can increase: Development is harder
  if an application needs to use database structures which aren't suited
  for the task at hand but have to be used as they are already present.
  It's also likely that adjustments of one application will have side
  effects on other applications ("why is there such an unecessary
  trigger??!"/"We don't need that data anymore!"). It's already hard
  with one database for a single application, when the developers
  don't/can't know all the use-cases.
Administration becomes harder: Which object belongs to which
  application? Chaos rising. Where do I have to look for my data? Which
  user is allowed to interact with which objects? What can I grant whom?
Upgrading: You'll need a version that is the lowest common denominator
  for all applications using it. That means that certain applications
  won't be able to use powerful features. You'll have to stick with
  older versions. It also increases development costs a bit.
Concurrency: Can you really be sure that there're no chronological
  dependencies between processes? What if one application modifies data
  that is outdated or should've been altered by another application
  first? What about different applications working on the same tables
  concurrently?

What I would suggest to you is to create a service layer which will be responsible for dealing with database access. This service can then be accessed by differents ways (a REST webservice might be an option).

A: @Vinod Bokare comment is correct, you must create jar of POJO's and use in both projects,
and @Heejeong Jang, It will be okay if each of our Spring apps has different table areas for insert, update, and delete.


text:
Q: Will a neutrino gas always stay at the same temperature? Does the neutrino gas pervading the universe always have the same temperature? Does it still have the temperature as the neutrino gas that emerged from the big bang?  Neutrinos don't interact, so how could the gas be cooled down (apart from space expansion)?

A: In thermal equilibrium, if we assume that the entropy conserved by expanding the universe, we can obtain the temperature of the photon gas:
$$T_\gamma = T_\gamma^0 (\frac{4}{11})^{\frac{1}{3}}(1+z)$$
where $T_\gamma^0$ is the initial temperature of photon gas and z is the redshift. Therefore, over time, the gas temperature decreases.

Another hand we can show that the temperature of neutrino gas equal to:
$$T_\nu = (\frac{4}{11})^{\frac{1}{3}}T_\gamma$$

A: The neutrino background cools as the universe expands. The reason for this is the de Broglie relation which relates the de Broglie wavelength to the momentum $p = h/\lambda$. As the universe expands, so does the de Broglie wavelength and thus the momentum decreases as the inverse of the scale factor of the universe.
As the universe expands, the neutrinos have a Fermi-Dirac distribution that looks like
$$F(p,T) = \frac{1}{\exp(pc/kT) + 1}\ ,$$
and this relates temperature to momentum.
As the momentum decreases as $a^{-1}$, then this evolving distribution can be characterised as having a temperature that also scales as $a^{-1}$, or $(1+z)^{-1}$, where $z$ is redshift. This is exactly the same scaling as the temperature of the CMB and so one can calculate that the temperature of the CMB and the temperature of the C$\nu$B ought to have a fixed ratio of $T_\gamma/T_\nu \simeq 1.41$ and thus $T_\nu \simeq 1.95$ K at the present epoch.
However, in order to calculate other properties of the C$\nu$B such as the rms speed or average energy, then this "temperature" $T_\nu$ can only be safely used while the neutrinos are ultrarelativistic with $k_B T_{\nu}\gg m_\nu c^2$. Once cooling gets to $k_B T_\nu \sim m_\nu c^2$, which for a neutrino rest-mass energy of say 0.1 eV, means $T_\nu \sim 1000$ K, then the neutrinos become non-relativistic. What this means is that although the neutrino momentum distribution is essentially "frozen" in its relativistic form and scales with the universal expansion as explained above, the same is not true for the energy or speed distributions of the neutrinos.
i.e. Although you can assign a "temperature" to the C$\nu$B of $\sim 1.95$ K today, the speed and kinetic energy distributions are not characterised by distributions at those temperatures. Indeed, once the neutrinos become non-relativistic then their kinetic energies scale as $p^2/2m_\nu$ and thus as $a^{-2}$ or $(1+z)^{-2}$.
Thus it is important to be careful about what you mean by the "temperature" of the C$\nu$B. For example, you cannot use $T_\nu \sim 1.95$ K to calculate an rms speed for present-day neutrinos in the C$\nu$B as $\sqrt{3k_BT/m_\nu}$. e.g. Using $\sqrt{3k_BT_\nu/m_\nu}$ would give you an rms speed of 21000 km/s for $m_\nu c^2 = 0.1$ eV, whereas a correct calculation would give more like 1600 km/s - a significant difference!
For this reason, I think most cosmologists prefer to work with the energy density of the C$\nu$B, which although one still has to deal with the transition between relativistic and non-relativistic neutrino species, at least has a well-defined meaning.


text:
Q: I don't get it (vba only works for half the columns) I. Do. Not. Understand.
I am trying to delete rows based on a value (target located in column 11).
This code only works for half the cells i want to delete, so i have to run it like 10 times (it goes from 520, then to 260, then 130, 65...)
My code seems simple enough but i still cannot quite figure out where the issue is...
Thanks for your help
Dim Target As String, i As Integer
Target = "Réduction ligne"
lastrow = Cells(Rows.Count, 11).End(xlUp).Row
For i = 1 To lastrow
    On Error Resume Next
    If Cells(i, 11).Value = Target Then
    Rows(i).EntireRow.Delete = True
   End If
Next i

A: The most important thing first:
On Error Resume Next

Please don't do that. It will make debugging your code a nightmare.

Why does your problem happen:
Now with this out of the way, let's look at the source of your problem. You have the following rows:
1 A
2 B
3 C
4 D

In your first loop iteration i = 1. Row 1 is deleted. Now your data looks like this:
1 B
2 C
3 D

In your second loop iteration i = 2. Since row 1 has been deleted, you are actually looking at the third original row.

How do I fix this:
This problem can be solved by iterating backwards:
For i = lastrow To 1 Step -1

A: Please, try the next code:
Sub efficientDeleteRows()
  Dim Target As String, lastRow As Long, i As Long, rngDel As Range
 Target = "Réduction ligne"
 lastRow = cells(rows.count, 11).End(xlUp).row
 For i = 1 To lastRow
    If cells(i, 11).value = Target Then
        If rngDel Is Nothing Then
            Set rngDel = cells(i, 11)
        Else
            Set rngDel = Union(rngDel, cells(i, 11))
        End If
    End If
 Next i
 If Not rngDel Is Nothing Then rngDel.EntireRow.Delete
End Sub


text:
Q: Mobile Phone Operating System Is it possible to to replace a mobile phones operating system from Android OS, v4.2 (Jelly Bean) to Blackberry os 10? and if so are there any instructions?

A: Not the right place to ask this, but I'll answer anyway. No, you can't. BlackBerry 10 is closed OS, and you don't have access to modify drivers and other stuff needed. Probably even requires specific peaces of hardware.


text:
Q: error: getting a passing "***" as "this" .... discards qualifiers The compiler is telling me I can't make the assignment in the constructor. I have extremely similar code in another class and it compiles just fine.
Dependency.h
class Dependency {
public:
    Dependency(std::function<void ()> const & func);

private:
    std::function<void ()> const call_back;
};

Dependency::Dependency(std::function<void ()> const & func){
    call_back = func;
}

A: Dependency::Dependency(std::function<void ()> const & func){
            call_back = func;
}

First, this constructs a Dependency object, and it's call_back member.  Then it enters the {}, which attempts to reassign func to call_back, which isn't allowed, because call_back is const.
Instead, we have to tell the compiler to construct call_back with func the first time, which uses this magic syntax:
Dependency::Dependency(std::function<void ()> const & func)
:call_back(func)
{
}

You use the same technique to call a specific constructor for parent classes.  Please note that it ignores the order you use here, the compiler will instead always construct the parent class(es) first, and then the members in the order they were declared in the class definition.

A: A const member can't be assigned after initialization. You have to ensure it is properly initialized in the constructor initialization list.
Dependency::Dependency(std::function<void()> const& func) : call_back(func) {}


text:
Q: how to get the uri of a cropped image selected from gallery using sound cloud in android studio if(requestCode == GET_FROM_GALLERY && resultCode == RESULT_OK) {
    try {
        Uri source_uri = imageUri;
        Uri dest_uri = Uri.fromFile(new File(getCacheDir(), "cropped"));
        // need to crop it to square image as CNN's always required square input
        Crop.of(source_uri, dest_uri).asSquare().start(MainActivity.this);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

// if cropping acitivty is finished,
// get the resulting cropped image uri and send it
// to 'Classify' activity

else if(requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK) {
    imageUri = Crop.getOutput(data);
    Intent i = new Intent(MainActivity.this, Classify.class);
    // put image data in extras to send
    i.putExtra("resID_uri", imageUri);
    // put filename in extras
    i.putExtra("chosen", chosen);
    // put model type in extras
    i.putExtra("quant", quant);
    // send other required data
    startActivity(i);
}

This code is meant to select an image from gallery crop it and then send the cropped image output to the image classifier activity.

A: I had to set the button that picks the image as shown in the code with the model initialized as model= "model.tflite"
 pick_image = findViewById(R.id.pick_picture);
        pick_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // filename in assets
                model = "model.tflite";
                Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(gallery, GET_FROM_GALLERY);
            }
        });

then the onActivity has to look like the one below
if(requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) {
            try {
                Uri source_uri = imageUri;
                Uri dest_uri = Uri.fromFile(new File(getCacheDir(), "cropped"));
                // need to crop it to square image as CNN's always required square input
                Crop.of(source_uri, dest_uri).asSquare().start(MainActivity.this);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // if cropping acitivty is finished, get the resulting cropped image uri and send it to 'Classify' activity
        else if(requestCode == Crop.REQUEST_CROP && resultCode == RESULT_OK){
            imageUri = Crop.getOutput(data);

            Intent i = new Intent(MainActivity.this, Classify.class);
            // put image data in extras to send
            i.putExtra("resID_uri", imageUri);
            // put filename in extras
            i.putExtra("chosen", chosen);

            // send other required data
            startActivity(i);

        }

        if (requestCode == GET_FROM_GALLERY && resultCode == RESULT_OK){
//            beginCrop(data.getData());
            try{
            Uri source =data.getData();
            Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
            Crop.of(source, destination).asSquare().start(this);
            }catch (Exception e){
                e.printStackTrace();
            }

        }else if (requestCode == Crop.REQUEST_CROP && resultCode ==RESULT_OK){
//            handleCrop(resultCode, data);
            Uri gon = Crop.getOutput(data);
            Intent i = new Intent(MainActivity.this, Classify.class);
            // put image data in extras to send
            i.putExtra("resID_uri", gon);
            // put filename in extras
            i.putExtra("chosen", chosen);

            // send other required data
            startActivity(i);
        }


text:
Q: Android - accessing files in native C/C++ code with Google Scoped Storage API I need to open files by file name in Android apps within native C/C++ code. The native code are 3rd party libraries that I would prefer not to modify, but they often require file name as an argument to read/write files. With the Google's "scoped storage" API and disabling native access to files in Android 10 or later, it's a real problem.
One well known solution is to get a file descriptor and use "proc/self/fd/FD_NUMER" trick, like:
       ParcelFileDescriptor mParcelFileDescriptor = null;

       String getFileNameThatICanUseInNativeCode(Context context, DocumentFile doc) {
           try {
                Uri uri = doc.getUri();
                mParcelFileDescriptor =
                        context.getContentResolver().openFileDescriptor(uri, "r");
                if (mParcelFileDescriptor != null) {
                    int fd = mParcelFileDescriptor.getFd();
                    return "/proc/self/fd/" + fd;
                }
            }
            catch (FileNotFoundException fne) {
                return "";
            }
        }

        // Don't forget to close mParcelFileDescriptor when done!

Passing this to native C/C++ code works, but only if the file is in phone main storage. If the user tries to open a file that is on external SD card inserted into the phone slot, it does not work - there is no read permission for the file opened this way. I can only grab the file descriptor int number and use fdopen(fd). But this will require modifying the source code of 3rd party libraries (open source or licensed), and a big headache, whenever the original source of these libraries is updated.
Is there any better solution to that problem? And no, I don't want to hear the solution with adding
android:requestLegacyExternalStorage="true"

to AndroidManifest.xml application section - Google threatens to disable that in the next version of Android in 2020, so a permanent solution is needed. Another easy but dumb solution is copying the entire (maybe huge) file that the user tries to open into private app directory. Dumb and useless...

A: Update May 19, 2020: just discovered: the READ_EXTERNAL_STORAGE permission lets you read files, but not list directory contents, when running on Android 11 and targeting API 30 (or higher in the future). I submitted it as a bug and just got "This is working as intended" reply (https://issuetracker.google.com/issues/156660903). If anyone cares, please comment there, and also at their "survey": https://google.qualtrics.com/jfe/form/SV_9HOzzyeCIEw0ij3?Source=scoped-storage I have no idea how to proceed developing apps on Android with all these limitations.
Update May 17 2020: Google has finally conceded and is permitting READ_EXTERNAL_STORAGE permission in Android 11 and beyond. After spending months in converting my apps to Storage Access Framework (SAF), I now take a week or two to convert it back, at least the reading files part, to regular file access... Thank you, Google! Thank you sarcastically, for the lost time and effort, and thank you sincerely, for at least partially understanding our point!
So, my previous answer listed below won't be needed anymore, sigh of relief!
After wasting another good day of my life on the Android "Scoped Storage" B.S., I found a solution that works, without modifying the source of 3rd party native libraries, provided that one has the source of these libraries and can build them.
My (very unsatisfactory) solution is: add the following option to C/C++ compile command:
-include "[some/path/]idiocy_fopen_fd.h"

and the idiocy_fopen_fd.h is as follows, as you can see, every call to regular fopen() is replaced by the idiocy_fopen_fd() code, which checks if the file name starts with "/proc/self/fd/", and if so, extracts the file descriptor number and calls fdopen() instead of fopen()... If someone has a better solution, preferably which would work also when you don't have the source code of the 3rd party libs, please share.
#ifndef fopen_fd

#include <stdio.h>
#include <string.h>
#include <unistd.h> // for dup()

#ifdef __cplusplus
extern "C" {
#endif

inline FILE* idiocy_fopen_fd(const char* fname, const char * mode) {
  if (strstr(fname, "/proc/self/fd/") == fname) {
    int fd = atoi(fname + 14);
    if (fd != 0) {
      // Why dup(fd) below: if we called fdopen() on the
      // original fd value, and the native code closes
      // and tries re-open that file, the second fdopen(fd)
      // would fail, return NULL - after closing the
      // original fd received from Android, it's no longer valid.
      FILE *fp = fdopen(dup(fd), mode);
      // Why rewind(fp): if the native code closes and
      // opens again the file, the file read/write position
      // would not change, because with dup(fd) it's still
      // the same file...
      rewind(fp);
      return fp;
    }
  }
  return fopen(fname, mode);
}
// Note that the above leaves the original file descriptor
// opened when finished - close parcelFileDescriptor in
// Java/Kotlin when your native code returns!

#ifdef __cplusplus
}
#endif

#define fopen idiocy_fopen_fd

#endif

A: Hi @gregko I managed to get the real path instead of the fd path and send it to my native activity which eases the burden a bit
  String getFileNameThatICanUseInNativeCode(Uri uri) throws FileNotFoundException {
      mParcelFileDescriptor =
              getApplicationContext().getContentResolver().openFileDescriptor(uri, "r");
      if (mParcelFileDescriptor != null) {
        int fd = mParcelFileDescriptor.getFd();
        File file = new File("/proc/self/fd/" + fd);
        String path = null;
        try {
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            path = Os.readlink(file.getAbsolutePath()).toString();
          }
        } catch (ErrnoException e) {
          e.printStackTrace();
        }

        return path;
      }
      else{
        return null;
      }
  }

With this code I basically do a full loop and then I get /storage/CC12-FF343/Games/game.zip instead of /proc/....


text:
Q: Want to seperate table border width using xslt Input html style::
border: #5f497a 3pt solid;
     or

border: 3pt #5f497a solid;
     or

border: solid #5f497a 3pt;

Hi all,
  These all are my possible html input style from which i have to fetch only the border width (3)  using xslt 1.0. Please help me..Thanks in advance..
Note:I will have always one digit before pt

A: This transformation:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="table">
  <xsl:apply-templates select="@style"/>
 </xsl:template>

 <xsl:template match="@style">

  <xsl:if test="string-length() >0">
    <xsl:variable name="vValues"
       select="substring-after(.,':')"/>
    <xsl:variable name="vNormalized" select=
    "translate(normalize-space(concat(';',$vValues)),
               ' ',
               ';')
    "/>

    <xsl:variable name="vEndingWidth" select=
     "substring-before($vNormalized,'pt;')"/>

    <xsl:variable name="vLength"
         select="string-length($vEndingWidth)"/>

    <xsl:value-of select="substring($vEndingWidth, $vLength)"/>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on the following XML document:
<t>

</t>

produces the wanted, correct results:
3
3
3


text:
Q: Unity Character flies above the ground whenever I start my game Every time I start my game the character starts to rise and fly above the ground. I don't understand how to fix it. I've tried to move the ground up but nothing's changed. 2D game if it matters.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player_Controller: MonoBehaviour
{
  public float speed = 0.1f;

  private void Update()
  {
      transform.position += new Vector3(speed, 0, 0) * Input.GetAxis("Horizontal");
      transform.position += new Vector3(0, speed, 0) * Input.GetAxis("Vertical");

      if(Input.GetAxis("Horizontal") < 0)//если влево
      {
           GetComponent<SpriteRenderer>().flipX = true;
      }
      if(Input.GetAxis("Horizontal") > 0)//если вправо
      {
           GetComponent<SpriteRenderer>().flipX = false;
      }

  }

}

A: You should be able to just add the Rigidbody Component to your Character GameObject, then enable gravity in the component and your character should just fall on the ground.
EDIT: If you find your character in the Unity Hierarchy (left hand side of the screen by default) and then to the inspector window (right hand side of the screen by default. At the bottom of the inspector, there should be an 'Add Component' button. Click that button and then search 'Rigidbody' in the search field that appears. Add the Rigidbody Component. By default, the enable gravity option should be ticked but if it isn't, just make sure you tick that box. When you run your game with gravity enabled, gravity should act on the GameObject with the 'Rigidbody' Component, pulling it to the ground
Also, make sure that you follow the same process as above to add the 'Mesh Collider' Component to your platform/ground - this will make your ground a 'Physical' object which will prevent your character falling straight through it
Hope this helps - let me know if it doesn't work


text:
Q: After a power failure, unable to mount the drive "Get a newer version of e2fsck" I have a desktop computer with Ubuntu Desktop 14.04.4 LTS 64-bit with an attached HDD USB 3.0 4TB Intenso 1 partition ext4 data drive only (no OS or Apps).
After a sudden power failure, I am unable to mount the drive (checked different host Linux machines with no result).
error message:
sudo mount /dev/sdd1 /mnt
mount: wrong fs type, bad option, bad superblock on /dev/sdd1,
       missing codepage or helper program, or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so

Tried with fsck, e2fsck with no result. The error message says "Get a newer version of e2fsck".
Tried with all available superblocks backups with no result.
Tried offline file/drive Linux checkers on the offline and UNmounted volume with no result.
Finally, I received the following error message for which I couldn't find any help online:
"has unsupported feature(s): metadata_csum".
e2fsck 1.42.9 (4-Feb-2014)
/dev/sdd1 has unsupported feature(s): metadata_csum
e2fsck: Get a newer version of e2fsck!

Can anyone help me take my data back?

A: I had the same problem and it took me some time to fix it, without formatting :)
Just follow this hint:

e2fsck: Get a newer version of e2fsck!

You need to download the latest version of e2fsck, compile it and then use this version.
Here are some steps to follow (use 1.43.1 or newer):
wget http://downloads.sourceforge.net/project/e2fsprogs/e2fsprogs/v1.43.1/e2fsprogs-1.43.1.tar.gz
tar xzf e2fsprogs-1.43.1.tar.gz
cd e2fsprogs-1.43.1
./configure # <== if this step fail, check the config.log file, it could just be that you are missing the "libc6-dev" package on your system
make
cd e2fsck/
./e2fsck

Voila!

A: metadata_csum stands for "Metadata Checksums" which is available for Ext4 file systems since Linux 3.6 but isn't supported by the file system tools until v1.43:

Support for checksums is sitting in the e2fsprogs WIP tree, which implies that it might appear in e2fsprogs 1.43.

Since Ubuntu Bionic has e2fsprogs v1.44.1 you don't have to build it from source any longer. Instead, if you have Ubuntu Trusty or Xenial, you can download the Deb packages for e2fsprogs for your architecture and install them with:
arch=$(dpkg --print-architecture)
sudo dpkg -i {e2fslibs,lib{ext2fs2,ss2,com{,-}err2}}_*_$arch.deb
sudo dpkg -i e2fsprogs_*_$arch.deb
sudo dpkg --configure --pending

Unfortunately the packages cannot be installed with a single DPKG invocation since one pre-depends on the other and must be installed and configured before it.

Note for non-x86* architectures: For whatever reason the package repositories behind the links above only have binary packages for the i386 and the amd64 architectures. If you need them for a different architecture you can download them from Launchpad.

A: You can compile source code and install latest version of e2fsck.
Clone repository that contains e2fsck source code.
git clone https://github.com/tytso/e2fsprogs.git

Make sure that you have necessary tools install to compile source code.
sudo apt install build-essential

Create directory for build.
cd e2fsprogs && mkdir build && cd build

Compile source code and install latest e2fsck.
../configure && make && cd e2fsck && sudo make install


text:
Q: Android : Click event is not triggered at time of animation I have a Button. On click of button i animate the TextView.
At the time of animation click is not working for texview.
 buttonclick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           final Animation animation = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 10.0f,
                    Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 10.0f);
            animation.setDuration(100000);
            textView.startAnimation(animation);
        }
    });

    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this,"Click",Toast.LENGTH_SHORT).show();
        }
    });

A: Animations are only animating views, not changing, its an illusion... You are using  TranslateAnimation, so you are moving your views "look", not the view itself. Ewentually you may use setFillAfter(true) method, then View will be clickable AFTER animation end (but your anim is long/infinite...).
Consider using Animator instead, which is changing "parameters" (in your case real position) of view with every frame of anim
ObjectAnimator animX = ObjectAnimator.ofFloat(textView, "x", newx);
ObjectAnimator animY = ObjectAnimator.ofFloat(textView, "y", newy);
AnimatorSet animSetXY = new AnimatorSet();
animSetXY.playTogether(animX, animY);
animSetXY.start();

A: try this
PropertyValuesHolder x = PropertyValuesHolder.ofFloat("x", 50f);
PropertyValuesHolder y = PropertyValuesHolder.ofFloat("y", 100f);
ObjectAnimator.ofPropertyValuesHolder(mTextView, x, y).start();

this way, you can animate whole view object--not just the contents.


text:
Q: How to secure and restrict user access to an API hosted in AWS Beaskstalk I am looking at hosting an API application in Beanstalk. I want to restrict access to everyone except for one person (tester) then when deploying it in production control who has access to it.
The API currently uses an API key and the user will need to authorize access but is there a way to restrict anyone finding the endpoint hitting the it. Do I need to look at restricting access via security groups? I will not know the IP address of the users.
I am potentially not looking at creating IAM access in AWS for this either.

A: The AWS solution is to make the API in Elastic Beanstalk private, so it can only be accessed from the VPC, and then place API Gateway in front of it.
If you don't want to use AWS API Gateway, or some sort of 3rd party API Gateway, and you don't know what your user's IP addresses are, then there is no way for you to prevent anyone from sending requests to the API endpoint while having your API accessible from the Internet.
Another option would be to make the API private (VPC only), and use AWS Client VPN, requiring your tester to establish a VPN connection before testing.


text:
Q: When a projection is an adjoint of another operator Suppose we have a Banach space $X$ and an idempotent operator $Q\colon X^*\to X^*$ with range isomorphic to $\ell_1$. Must $Q$ be an adjoint to some idempotent operator on $X$? In other words, is $Q$ $w^*$-$w^*$-continuous?

A: Let $X = C[0,1]$ so $X^* = M[0,1]$, the signed Borel measures on $[0,1]$.  Define $Q: X^* \to X^*$ so that $Q \mu$ is the measure supported on $\{1/n: n \in {\mathbb N}\}$ with
$(Q\mu)(\{1/k\}) = \mu((1/(k+1),1/k])$.
This is not $w^*-w^*$ continuous: as $t \to 1/n+$, the point mass $\delta_t$ converges $w^*$ to $\delta_{1/n}$, but $Q \delta_t = \delta_{1/(n-1)}$ for $t \in (1/n, 1/(n-1)]$.

A: No. Consider $X = c_{0} \mathbin{\oplus_{\infty}} \ell^1$ so that $X^{\ast} = \ell^{1} \mathbin{\oplus_1} \ell^{\infty}$ and take a Banach limit $L: \ell^{\infty} \to \mathbb{R}$. Then $L \in (\ell^{\infty})^\ast \smallsetminus \ell^{1}$, so it is not weak$^\ast$-continuous: the sequence $h_n = (1,\ldots,1,0,\ldots)$ with $n$ nonzero entries weak$^\ast$-converges to the constant sequence $1$ but $1 = L(1) \neq 0 =\lim_{n\to\infty}L(h_n)$.
Let us identify $\mathbb{R}$ with the subspace of constant sequences in $\ell^\infty$.
The range of the map $Q\colon \ell^{1} \mathbin{\oplus_1} \ell^{\infty} \to \ell^{1} \mathbin{\oplus_1} \ell^{\infty}$ given by $Q(g,h) = (g,Lh)$ is $\ell^{1} \mathbin{\oplus_1} \mathbb{R} \subset \ell^1 \mathbin{\oplus_1} \ell^\infty$ and $Q$ is idempotent because $L$ fixes the space of constant sequences. But $Q$ is not weak$^\ast$-continuous because $(0,1)$ is the weak$^\ast$-limit of $(0,h_n)$ while $(0,L(1)) = (0,1) \neq (0,0) = \lim_{n\to\infty}(0,Lh_n)$.


text:
Q: What values of resistor and capacitor to use for AVR reset pin isolation? Background...
I'm a newbie to AVR applications. I recently built two ATTINY13-based circuits (glorified LED blinkers) which worked correctly (independently) on the breadboard. When I combined them on a solder perfboard with a shared power supply, things went haywire. After much investigation, it appeared they were constantly resetting.
I had left pin 1 (reset) of each micro un-connected. I researched proper ways of handling the reset pin and from this implemented the following:

*

*Added a 100uF electrolytic capacitor in parallel with the power supply to help with any potential current draw the power supply would be too "slow" to deal with.

*Added a 4.7K resistor from VCC to RESET

*Added a 0.1uF ceramic capacitor from GND to RESET
These steps solved the problem completely.
The question:
The page I linked above is providing advice when doing ISP (in-system programming) which I am not doing (yet). (I'm programming the micros separately with no other components connected to them.)
I've seen several different values of capacitor (10nF, 0.1uF, etc.) and resistor (4.7K, 10K, etc.) and am not sure what factors alter these values. Can anyone shed some light on how reset pin isolation works, and how to calculate component values to use? Can you explain what values to use if there is no in-system programming header?

A: I always just use a 10k pullup resistor to Vcc on the /Reset pin and have never had any problems. It's also generally a good idea to include a 100nF capacitor near the Vcc pin between Vcc and GND for stable chip operation. In my opinion the capacitor on the reset pin is not necessary, which is to say I have never included one in any AVR circuit I have developed (and I've developed lots) and it's never caused me grief.

A: Atmel AVR042: AVR Hardware Design Considerations tell us that the capacitor on the reset pin is not necessary. Personally I think it's overkill. There is no reason for you to continue making dozens of AVR circuits, each and every one with that redundant capacitor.
As for the reset pullup resistor:

The reset line has an internal pull-up resistor, but if the
  environment is noisy it can be  insufficient and reset can therefore
  occur sporadically. Refer to datasheet for value of  pull-up resistor
  on specific devices.  Connecting the RESET so that it is possible to
  enter both high-voltage programming  and ordinary low level reset can
  be achieved by applying a pull-up resistor to the  RESET line. This
  pull-up resistor makes sure that reset does not go low unintended.
  The pull-up resistor can in theory be of any size, but if the
  Atmel®AVR® should be  programmed from e.g. STK500/AVRISP the pull-up
  should not be so strong that the  programmer cannot activate RESET by
  draw the RESET line low. The recommended  pull-up resistor is 4.7kΩ or
  larger when using STK500 for programming. For  debugWIRE to function
  properly, the pull-up must not be smaller than 10kΩ.

If you take a look at professional products that incorporate the AVR micros, such as the Arduino, its numerous clones, dozens of dev kits, you'll find that most use a 4.7kΩ or 10kΩ resistor.
And particularily for your ATtiny13, its datasheet specifies that the pullup should ideally range [20kΩ, 80kΩ].


text:
Q: mediaelement.js - Prevent Seek Forward / Allow Seek Backwards Can you please give me an idea or sample that I can prevent seek forward to the seeking bar but will allow to seek backwards?
This is what I found but it keeps on a loop:
media.addEventListener('seeked', function(e) {
    // player.setCurrentTime(0);
    // player.play();
}, true);

A: I recently had the same requirement.
But didn't really want to modify the source file.
Here's another way of doing it without modifying the source:
  var _player = $("#my_video_1")[0].player; //<-- get the reference to the player

  old = _player.media.setCurrentTime; //<-- store the native setCurrentTime temporarily

  _player.media.setCurrentTime = function(time) { //<-- override it with our own method
      if(time <= this.currentTime){
          old.apply(this,[time]); //<-- call the stored method if our conditions are met
      }
  };

A: What i did was this: Inside the uncompressed version of mediaelement library find a row:
media.setCurrentTime(newTime);
Add above the previous line:
if ( newTime <= media.currentTime )
Eventually you have:
if ( newTime <= media.currentTime )
media.setCurrentTime(newTime);

which means that if the time to be seeked is lower or equal to the player's current time
then allow seeking.


text:
Q: Adequate way to connect sensors far away from arduino I have a simple setup when I have to read analog values from a light sensor, and I need to put it far away from the arduino (several meters away). I want to know how can I create a wired reliable connection from the arduino to the sensor.

simulate this circuit – Schematic created using CircuitLab
Here is the function that activates the system:

void photoResistorActivation () {
  int photoResistor = 1024 - analogRead(PHOTO_RESISTOR_PIN);
  if (DEBUG) {
    Serial.println (photoResistor, DEC);
  }
  if (photoResistor >= LIGHT_THRESHOLD) {
    personDetected = false;
  }
  else {
    if (personDetected == false) {
      trigger = true;
      personDetected = true;
    }
  }
}

Edit: I have received valuable feedback in the answers about how to avoid noise, but I want to clarify that I'm asking about physical connection (cables, connectors and so on). What kind of cables should I use? Jumper cables?
Thank you

A: I would consider using some capacitors, clamping diodes, and output resistors very close to the arduino.
The long wires will have capactive and inductive loads. Bumps to the wire will create noise spikes.

*

*The output resistors (input to the arduino) will limit the spike based on the current surge (should be low, 10k resistor should be fine).

*The capacitor will stabilize the voltage, select the capacitor value based on a low pass filter RC equation and the expected frequency of the light changing (f = 1/2*piRC). If it's just ambient light in a room go with 10uF or whatever is available, if its a strobing diode, calculate the filter value.

*For the clamping diode, pick a fast response time diode that clamps at a little over 5V so the noise spikes, and ESD, from tapping the wire doesn't kill the input pin on your arduino. The P6KE6V8CA should do the trick.

A: Your question is a bit vague.
The best solution would be to put an ADC behind the sensor, since digital transmission is a lot more resitant against distortion. If this is possible you might want to transmit it even differentially (invert the signal and output either plus and minus your high level or 0).
If this is not possible you want at least a twisted pair cable or a shielded cable to reduce the distortion. The best connection should be a BNC connector on the board and a coax cable.
Also if you can't put an ADC behind the sensor, you might still want to amplify your analogue signal depending on what the sensor outputs.


text:
Q: android-asycn-http: Never send the http request I'm using android-async-http 1.4.5, but I found it never calls my server, here's my code :
public class HttpUtils {
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
    params.setUseJsonStreamer(true);
    client.get(url, params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
    params.setUseJsonStreamer(true);
    Log.i("URL", url);
    client.post(url, params, responseHandler);
  }
}

Here's how I define my handler:
public abstract class JsonResponseHandler extends AsyncHttpResponseHandler {
  private static final String TAG = "JSON_RESPONSE_HANDLER";

  public abstract void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject);

  public abstract void onFailure(int statusCode, Header[] headers, JSONObject jsonObject);

  @Override
  public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
    Log.i(TAG, "on success");
    onSuccess(statusCode, headers, parseObject(responseBody));
  }

  @Override
  public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
    Log.i(TAG, "on failure");
    onFailure(statusCode, headers, parseObject(responseBody));
  }

  private JSONObject parseObject(byte[] response) {
    JSONObject jsonObj = null;
    try {
      String json = new String(response, "UTF-8");
      jsonObj = new JSONObject(json);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return jsonObj;
  }
}

After some debug work, I found my code actually execute client.post(...), but my server didn't receive any call from it.
EDIT
Here's how I use it in my test case :
public class VerifyCodeTest extends TestCase {

  private static final String TAG  ="VERIFY_CODE_TEST";

  public void testGetVerifyCode(){
    Log.i(TAG, "Hello World");

    VerifyCodeTransaction vc= new VerifyCodeTransaction("167xxxx137");
    vc.execute(new JsonResponseHandler() {

      @Override
      public void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject) {
        Log.i(TAG, "SUCCESS");
        Log.i(TAG, jsonObject.toString());
      }

      @Override
      public void onFailure(int statusCode, Header[] headers, JSONObject jsonObject) {
        Log.i(TAG, "FAILURE");
        Log.i(TAG, jsonObject.toString());
      }
    });
  }
}

A: i don't know if you encounter this problem only in your TestCase or also in your App. I think the library doesn't work well for unit tests!! source:https://github.com/loopj/android-async-http/issues/321
i had a similar problem with the library in the past, i solved it by compiling the library from the source code in github repo
Maybe it's better that you use the latest version of the library :)


text:
Q: psycopg2 insert statement with LIKE clause containing % sign Can't execute a psycopg2 insert query (Postgres db), which uses the best practice %s sign for inserting and contains a LIKE statement which includes a % sign.
% sign in LIKE statement is interpreted as an insert placeholder.
'IndexError: tuple index out of range' is thrown.
Tried escaping % with backslash, didn't work out.
with psycopg2.connect(some_url) as conn:
    with conn.cursor() as cur:
        query = """
        SELECT id
        FROM users
        WHERE surname IN %s AND named LIKE '%john'
        """

        cur.execute(query, (tuple(["smith", "mcnamara"]),))
        data = cur.fetchall()

A: Try using a placeholder also for the LIKE expression, and then bind a literal with a wildcard to it:
query = """
    SELECT id
    FROM users
    WHERE surname IN %s AND named LIKE %s"""

cur.execute(query, (tuple(["smith", "mcnamara"]), "%John",))
data = cur.fetchall()

A: try this one:
with psycopg2.connect(some_url) as conn:
    with conn.cursor() as cur:
        query = """
        SELECT id
        FROM users
        WHERE surname IN %s AND named LIKE '%sjohn'
        """

        cur.execute(query, (tuple(["smith", "mcnamara"]), '%'))
        data = cur.fetchall()


text:
Q: Second identical RADEON card not automatically detected I purchased a second radeon dual-head card so that I can have 3 monitors. I'm running kubuntu, and usually, I just pop open system settings and manage the monitors. My new card/monitor do not show up in that interface, but some part of the system sees them. I currently do not have an xorg.conf file, since this has always "just worked" for me before.
$ lspci | grep VGA
01:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Caicos XT [Radeon HD 7470/8470 / R5 235/310 OEM]
03:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Caicos XT [Radeon HD 7470/8470 / R5 235/310 OEM]

# lshw -c video
  *-display
       description: VGA compatible controller
       product: Caicos XT [Radeon HD 7470/8470 / R5 235/310 OEM]
       vendor: Advanced Micro Devices, Inc. [AMD/ATI]
       physical id: 0
       bus info: pci@0000:01:00.0
       version: 00
       width: 64 bits
       clock: 33MHz
       capabilities: pm pciexpress msi vga_controller bus_master cap_list rom
       configuration: driver=radeon latency=0
       resources: irq:28 memory:e0000000-efffffff memory:f7e20000-f7e3ffff ioport:e000(size=256) memory:f7e00000-f7e1ffff
  *-display
       description: VGA compatible controller
       product: Caicos XT [Radeon HD 7470/8470 / R5 235/310 OEM]
       vendor: Advanced Micro Devices, Inc. [AMD/ATI]
       physical id: 0
       bus info: pci@0000:03:00.0
       version: 00
       width: 64 bits
       clock: 33MHz
       capabilities: pm pciexpress msi vga_controller bus_master cap_list rom
       configuration: driver=radeon latency=0
       resources: irq:30 memory:d0000000-dfffffff memory:f7d20000-f7d3ffff ioport:d000(size=256) memory:f7d00000-f7d1ffff

Some interesting parts of /var/log/Xorg.0.log:
[     4.752] (==) Log file: "/var/log/Xorg.0.log", Time: Tue Jan 24 17:00:38 2017
[     4.754] (==) Using system config directory "/usr/share/X11/xorg.conf.d"
[     4.767] (==) No Layout section.  Using the first Screen section.
[     4.767] (==) No screen section available. Using defaults.
[     4.767] (**) |-->Screen "Default Screen Section" (0)
[     4.767] (**) |   |-->Monitor "<default monitor>"
[     4.768] (==) No monitor specified for screen "Default Screen Section".
    Using a default monitor configuration.
[     4.768] (==) Automatically adding devices
[     4.768] (==) Automatically enabling devices
[     4.768] (==) Automatically adding GPU devices

...snip...
[     4.779] (II) xfree86: Adding drm device (/dev/dri/card0)
[     4.779] (II) xfree86: Adding drm device (/dev/dri/card1)
[     4.779] (EE) /dev/dri/card1: failed to set DRM interface version 1.4: Permission denied
[     4.779] (II) config/udev: Ignoring already known drm device (/dev/dri/card1)
[     4.780] (--) PCI:*(0:1:0:0) 1002:6778:1028:2120 rev 0, Mem @ 0xe0000000/268435456, 0xf7e20000/131072, I/O @ 0x0000e000/256,    BIOS @ 0x????????/131072
[     4.780] (--) PCI: (0:3:0:0) 1002:6778:1028:2120 rev 0, Mem @ 0xd0000000/268435456, 0xf7d20000/131072, I/O @ 0x0000d000/256,    BIOS @ 0x????????/131072

If I do set up an xorg.conf with the following contents:
Section "Device"
    Identifier  "First"
    Driver      "radeon"
    BusID       "PCI:1:0:0"
EndSection

Section "Device"
    Identifier  "Second"
    Driver      "radeon"
    BusID       "PCI:3:0:0"
EndSection

The Xorg.0.log looks like:
[     4.186] (==) Log file: "/var/log/Xorg.0.log", Time: Tue Jan 24 17:11:22 2017
[     4.188] (==) Using config file: "/etc/X11/xorg.conf"
[     4.188] (==) Using system config directory "/usr/share/X11/xorg.conf.d"
[     4.196] (==) No Layout section.  Using the first Screen section.
[     4.196] (==) No screen section available. Using defaults.
[     4.196] (**) |-->Screen "Default Screen Section" (0)
[     4.196] (**) |   |-->Monitor "<default monitor>"
[     4.198] (==) No device specified for screen "Default Screen Section".
    Using the first device section listed.
[     4.198] (**) |   |-->Device "First"
[     4.198] (**) |   |-->GPUDevice "Second"
[     4.198] (==) No monitor specified for screen "Default Screen Section".
    Using a default monitor configuration.
[     4.198] (==) Automatically adding devices
[     4.198] (==) Automatically enabling devices
[     4.198] (==) Automatically adding GPU devices

Which makes me think it's trying to use the second video card as some type of rendering helper for the first? Also, I'm not sure exactly what the permission denied from the DRM line is all about - googling isn't turning up much for help there. The new monitor does have the kubuntu on a black screen (is that the startup framebuffer or something? not sure what that is...)
If it helps any, I'd be happy to attach the full Xorg.0.log file, or dmesg, or whatever.
Gigantic thanks in advance if you read all the way through this.

A: I am not a Radeon owner but I think multiple-card setup doesn't work with open-source driver https://www.x.org/wiki/RadeonFeature/
Give a try to the binary driver: https://help.ubuntu.com/community/BinaryDriverHowto/AMD


text:
Q: VueJS v-model and data binding between components I am having troubles with how vuejs binds the data. I have a parent Vue.component which is the handles the layout of my form and i have child vue.component which handle the different input groups. I am having troubling getting the data from the child component to sync with the parent component for when i do my form submit in future.
I currently have my file like this:
var title = "";
Vue.component('create_new_entry', {
    template: '

{{title}}

<section_title></section_title>

',
    data    : function() {
        return {
            title: title
        };
    },
});
Vue.component('section_title', {
    template: '

{{title}}
<input type="text" class="form-control" v-model="title">
',
    data    : function() {
        return {
            title: title
        };
    },
    methods : {
        test: function() {
            console.log(this);
        }
    }
});

I am not sure where i am going wrong and as much as i try to the documentation im still having trouble with how the data get bound and updated.

A: You are declaring two entirely separate fields, one in each component, and there is nothing tying them together other than they share the same name. Vue is treating those as two separate fields, when one changes, the other does not. The fields are private and internal to the component instances.
Shared state should be passed down to child components as props, and should be passed up to parent components as events. There are a few ways of approaching this, the simplest being adding a prop and event. A more complex way would be to use a state management tool like vuex. https://github.com/vuejs/vuex
Here is a simple example using a prop and an event.
Prop documentation: https://v2.vuejs.org/v2/guide/components.html#Props
Event documentation: https://v2.vuejs.org/v2/guide/components.html#Custom-Events
var title = "";
Vue.component('create_new_entry', {
    template: '

{{title}}

<section_title :title="title" @title-changed="changeTitle"></section_title>

',
    data    : function() {
        return {
            title: title
        };
    },
    methods: {
        changeTitle(newTitle) {
            this.title = newTitle;
        }
    }
});
Vue.component('section_title', {
    template: '

{{title}}
<input type="text" class="form-control" v-model="innerTitle">
',
    props: ['title'],
    data    : function() {
        return {
            innerTitle: this.title
        };
    },
    methods : {
        test: function() {
            console.log(this);
        }
    },
    watch: {
        title(val){
            this.innerTitle = val;
        },
        innerTitle(val) {
            this.$emit('title-changed', val);
        }
    }
});

The parent component passes its title component down to the child component so it has access to it. The child component is unable to modify its props, so it copies the value of the prop to a local data field innerTitle. The input in the child component is bound to the innerTitle using v-model. A watch is added on the innerTitle so that any time it changes, it emits an event title-changed. The parent component listens for the title-changed event, and whenever it occurs, the parent updates its title field to that new value.
The child component also has a watch on the title prop so that if the parent's title value changes for any other reason, the child component will be able to update its internal state to match the parent's new value.
As stated before, you could also use Vuex, or use another Vue instance as a bus as explained here https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication


text:
Q: Parse serialized date in Grails with proper time zone I'm trying to bind date in Grails App. In application.yml I have databindings for default JavaScript date formats:
  grails:
    databinding:
      dateFormats:
        - "yyyy-MM-dd'T'hh:mm:ss.S'Z'"
        - "yyyy-MM-dd'T'HH:mm:ss'Z'"

In Groovy I'm creating object from params def entity = new Entity(params) and everything binds OK, but...
The problem is that I have wrong time zone in my Grails app, i.e.:

*

*In AngularJS I'm creating new Date - Thu Oct 22 2015 00:00:00 GMT+0200 (CEST) (this is string representation of Date object)

*Next I'm sending it via $http service, JSON payload looks like this: { date: "2015-10-21T22:00:00.000Z", another: "another:, property: "property"  }.
Date looks fine right now, Z at the end means it is UTC so Thu Oct 22 2015 00:00:00 GMT+0200 (CEST) - 2 hours => 2015-10-21T22:00:00.000Z

*In Grails I'm doing def entity = new Entity(params) and here is problem, entity.date is equals to Wed Oct 21 22:00:00 CEST 2015 which means that Groovy/Grails parsed string 2015-10-21T22:00:00.000Z as CEST time zone not UTC
So how can I force Grails to load date with proper format?
PS
Both the web browser and computer is working with CEST time zone.
I'm using Grails 3.0

A: Proper datetime string is yyyy-MM-dd'T'HH:mm:ss.SSSX.
In next versions this should be fixed and JavaScript datetime strings will be parsed via default parser.
More:
https://github.com/grails/grails-core/issues/9367
https://github.com/grails/grails-core/issues/9368


text:
Q: ImageMagick `-duplicate` but to beginning of sequence -duplicate
convert img*.png -duplicate 3 out.gif

makes
0 1 2 2 2 2

where 0 is img0.png, and 1 is img1.png, etc, making a GIF. But can I make below?
0 0 0 0 1 2 2 2 2

that is, append to end and start? I get I can use indexing to make
0 1 2 2 2 2 0 0 0

which is identical in a loop, but I need the 0s at start in context.

A: TL;DR for 0 0 0 1 2 3 ... 20 21 21 21 (any number of images) do
convert img*.png -write mpr:imgs -delete 0--1 mpr:imgs[0,0,0,1--1,-1,-1] out.gif

Using ImageMagick v6 on Windows command line, this command will let you arrange the order and number of images in any way you need.
convert img*.png -write mpr:imgs -delete 0--1 mpr:imgs[0,1,2,2,2,2,0,0,0] out.gif

That reads the 3 input images, copies them all into a memory register named "mpr:imgs", deletes the input images from the command, then reads the images from that memory register as you specify in the square brackets. The image index 0 is the first image read into the command, 1 is the second, etc.
Also, using -duplicate you can specify which image in the list you want to use according to their order in the list. This command will give the same result as the one above...
convert img*.png -duplicate 3 -duplicate 3,0 out.gif

The command reads the three images, then -duplicate 3 makes 3 more of the last image in the list, then -duplicate 3,0 makes 3 more of the first image in the list, index 0.
Another approach would be to use ( -clone ... ) inside parentheses to create the number of duplicates in the order you want.
convert img*.png ( -clone 2,2,2 -clone 0,0,0 ) out.gif

That reads the 3 input images, clones the third image 3 times, then clones the first image 3 times, giving the same result as the commands above.
These commands are in Windows syntax. For a *nix OS you'd have to escape the parentheses with backslashes "\(...\)".
Also helpful are -swap, -reverse, -insert, and -delete  to manipulate the order of images in the list.

A: You should be able to load your first image, make any duplicates you need, then load the second and make duplicates and load the third and make any duplicates:
convert img0.png -duplicate 3 img1.png img2.png -duplicate 3 ...

will give your desired image sequence:
0 0 0 0 1 2 2 2 2