text:
Q: parser.setFeature vs parser.setValidating What is the diffrence between the following:
parser.setFeature("http://xml.org/sax/features/validation",true);
and
parser.setFeature("http://apache.org/xml/features/validation/schema",true);
and
parser.setValidating(true);

I found the exact question twice on googling but not the answer
I am using org.apache.commons.digester, i am calling setFeature or setValidating on the digester.

A: I was searching for the answer to the same question. You probably already found your answer but for others like me who arrive at this thread.
From what I can see it is implementation specific. SAX doesn't really seem to have a real specification (the spec is their website saxproject.org). At least I didn't find any reference in a spec or javadoc (maybe I overlooked) that isValidating should be in sync with the validation feature.
public boolean isValidating()
Indicates if this SAXParserFactory is configured to produce parsers that validate
XML documents as they are parsed.

But if you look, for example, at the implementation from Xerces: org.apache.xerces.jaxp.SAXParserFactoryImpl you will notice that they internally use the validation setting (isValidation, setValidating) for the validation feature.

*

*setFeature
else if (name.equals(VALIDATION_FEATURE)) {
    setValidating(value);
    return;
}

*getFeature
else if (name.equals(VALIDATION_FEATURE)) {
    return isValidating();
}

Or if you look at the Sun source
public void setValidating(boolean validating) {
    putInFeatures(VALIDATION_FEATURE, validating);
}

(Example from openjdk-6-src-b31-15_apr_2014)
Another one is the oracle xmlparserv2 from Oracle XDK
Some sample test to prove this (you need the oracle xmlparserv2 jar and you also need a META-INF/services/javax.xml.parsers.SAXParserFactory file with only this org.apache.xerces.jaxp.SAXParserFactoryImpl because the oracle jar is ... well rather dominant)
public class SaxParserTest {
    @Test
    public void validationFeatureTestXerces() throws Exception {
        SAXParserFactory parserFactory = org.apache.xerces.jaxp.SAXParserFactoryImpl.newInstance();

        parserFactory.setFeature("http://xml.org/sax/features/validation", false);
        Assert.assertFalse(parserFactory.isValidating());
        parserFactory.setFeature("http://xml.org/sax/features/validation", true);
        Assert.assertTrue(parserFactory.isValidating());

        parserFactory.setValidating(true);
        Assert.assertTrue(parserFactory.getFeature("http://xml.org/sax/features/validation"));
        parserFactory.setValidating(false);
        Assert.assertFalse(parserFactory.getFeature("http://xml.org/sax/features/validation"));
    }

    @Test
    public void validationFeatureTestOracle() throws Exception {
        SAXParserFactory parserFactory = oracle.xml.jaxp.JXSAXParserFactory.newInstance();

        parserFactory.setFeature("http://xml.org/sax/features/validation", false);
        Assert.assertFalse(parserFactory.isValidating());
        parserFactory.setFeature("http://xml.org/sax/features/validation", true);
        Assert.assertTrue(parserFactory.isValidating());

        parserFactory.setValidating(true);
        Assert.assertTrue(parserFactory.getFeature("http://xml.org/sax/features/validation"));
        parserFactory.setValidating(false);
        Assert.assertFalse(parserFactory.getFeature("http://xml.org/sax/features/validation"));
    }

}


text:
Q: XPath: How do I capture the previous element? I have such a construction

File name

Download

I need to capture the link a and its name p using CSS and XPath. I'm trying to do the following, first I find using the CSS selector all files whose href values end in .pdf (a[href$=".pdf"]):
for i in response.css('a[href$=".pdf"]'):
    link = i.css('::attr("href")').get()
    name = i.xpath(?????????)
    print(name, link)

How do I capture the text in the p element using XPath?

A: Starting from a
This XPath,
//a[.="Download"]/preceding-sibling::p[1]

will select the first p element siblings preceding each a element whose string value equals "Download".

Starting from p
This XPath,
//p[.="File name"]/following-sibling::a[1]

will select the first a element siblings following each p element whose string value equals "File name".

In either case, you can select the text node child by appending /text() to the XPaths.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make use of cached data in my app? How to cache list data(images and names) in retrofit? Any suitable example for caching data will be more helpful?

A: ok. first of all you have to check headers coming in your api through postman. There you will see "Cache-Control" header. In this header, there has to be public cache value if you want to cache that api. Here is the code :
In your ApiClient.class where u kept your base URL, make this method :
public static CacheControl getCacheControl(CachePolicy cachePolicy) {
   switch (cachePolicy) {
       case CACHE_ONLY:
           return CacheControl.FORCE_CACHE;
       case NETWORK_ONLY:
           return CacheControl.FORCE_NETWORK;

       case NETWORK_ELSE_CACHE:
           return new CacheControl.Builder().maxAge(1, TimeUnit.MINUTES).maxStale(1, TimeUnit.MINUTES).build();

       case FRESH_CASHE_ELSE_NETWORK:
           return new CacheControl.Builder().maxAge(1, TimeUnit.MINUTES).minFresh(1, TimeUnit.MINUTES).build();

       case CACHE_ELSE_NETWORK:
          return new CacheControl.Builder().immutable().build();

   }
   return null;

}
Now make an enum class to keep these constants :
 public enum CachePolicy {
 CACHE_ONLY,
 NETWORK_ONLY,
 NETWORK_ELSE_CACHE,
 FRESH_CASHE_ELSE_NETWORK,
 CACHE_ELSE_NETWORK
 }

Paste this method in your ApiClient class with your base url :
public static Retrofit getClientAuthenticationWithCache(Context context, CacheControl
       cacheControl) {
   String URL_BASE = "your base url";
   long cacheSize = 10 * 1024 * 1024;  //10MiB
   Cache cache = new Cache(context.getCacheDir(), cacheSize);

   Interceptor interceptor = new Interceptor() {
       @Override
       public Response intercept(Chain chain) throws IOException {
           Request request = chain.request();
           request = request.newBuilder().cacheControl(cacheControl).build();
           return chain.proceed(request);
       }
   };

   OkHttpClient okHttpClient = new OkHttpClient.Builder()
           .cache(cache)
           .addInterceptor(interceptor)
           .build();

   Retrofit.Builder builder = new Retrofit.Builder()
           .baseUrl(URL_BASE)
           .client(okHttpClient)
           .addConverterFactory(GsonConverterFactory.create());

   return builder.build();

}
Now use this method in the activity/fragment where you are getting response as follow :
ApiClient.getClient(applicationContext, ApiClient.getCacheControl(CachePolicy.NETWORK_ELSE_CACHE)).create(ApiInterface::class.java)


text:
Q: Using Python cURL to upload to SMB I am trying to covert the follow curl command in CLI to python:

curl --upload-file some.file -u 'username:p@ssw0rd'
  smb://192.168.0.1/C$/local/path

Which works fine! But I can not get it to work with pycURL or requests in python.
note: I do not want to use pySMB.


text:
Q: How do I remove "\U0000fffc" from a string in Swift? I have added an image to a textfield, and wish to remove it again. I've tried the following two lines to no avail?
string = string.stringByReplacingOccurrencesOfString("\\U0000fffc", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
string = string.stringByReplacingOccurrencesOfString("\U0000fffc", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

Any help would be greatly appreciated, thanks so much!

A: The method stringByReplacingOccurrencesOfString can work on parts of the string or the whole string.
For example, this works on the entire string, by giving it the range from start of the string to the end:
let original = "First part \\U0000fffc Last part"

let originalRange = Range<String.Index>(start: original.startIndex, end: original.endIndex)

let target = original.stringByReplacingOccurrencesOfString("\\U0000fffc", withString: "", options: NSStringCompareOptions.LiteralSearch, range: originalRange)

println(target) // prints "First part  Last part"

A: Unicode escape sequences are differently in Swift from those in Objective-C, the Unicode character U+FFFC is escaped as \u{fffc}:
This is your string:
var string = "Hello\n\n\u{fffc}"
println(string.dataUsingEncoding(NSUTF32BigEndianStringEncoding)!)
// <00000048 00000065 0000006c 0000006c 0000006f 0000000a 0000000a 0000fffc>

Now remove all U+FFFC characters:
string = string.stringByReplacingOccurrencesOfString("\u{fffc}", withString: "")
println(string.dataUsingEncoding(NSUTF32BigEndianStringEncoding)!)
// <00000048 00000065 0000006c 0000006c 0000006f 0000000a 0000000a>

Note that options: and range: are optional parameters and not
needed in this case.

Update for Swift 3/4:
var string = "Hello\n\n\u{fffc}"
print(string.data(using: .utf32BigEndian)! as NSData)
// <00000048 00000065 0000006c 0000006c 0000006f 0000000a 0000000a 0000fffc>

string = string.replacingOccurrences(of: "\u{fffc}", with: "")
print(string.data(using: .utf32BigEndian)! as NSData)
// <00000048 00000065 0000006c 0000006c 0000006f 0000000a 0000000a>


text:
Q: AttributeError: 'str' object has no attribute 'insert' I'm trying to insert a piece of text into my linked list. However, when ever I try to do this I get an error "AttributeError: 'str' object has no attribute 'insert'". I am writing this in python 3.3.
class Node:
def __init__(self, item= None , link= None ):
    self.item = item
    self.next = link

def __str__(self):
    return str(self.item)

class List:
def __init__(self):
    self.head = None
    self.count = 0

def is_empty(self):
    return self.count == 0

def is_full(self):
    return False

def reset(self):
    self.__init__()

def __len__(self):
    return self.count

def _getNode(self, index):
    node = self.head
    for _ in range(index):
        node = node.next
    return node

def insert(self, index, item):
    if index < 0:
        index = 0

    elif index > len(self):
        index = len(self)

    if index == 0:
        self.head = Node(item, self.head)
    else:
        node = self._getNode(index - 1)
        node.next = Node(item, node.next)

    self.count += 1

def delete(self, index):
    if self.is_empty():
        raise IndexError("List is empty")
    if index < 0 or index >= len(self):
        raise IndexError("Index is out of range")

    if index == 0:
        self.head = self.head.next
    else:
        node = self._getNode(index - 1)
        node.next = node.next.next

    self.count -= 1

import LinkedList
text= LinkedList.List()

def insert_num(line,text):
    text.insert(line - 1,text)

def delete_num(line):
    if line is None:
        text.reset
    else:
        text.delete(line)

def print_num(line):
    if line is None:
        i= 0
        while i< line.count:
            item= text._getNode(i)
            print (item)
    else:
        print(text._getNode(line))

while True:
    print("1. Insert")
    print("2. Delete")
    print("3. Print")
    print("4. Quit")
    command = int(input())
    if command == 1:
        line = int(input("At what line do you wish to insert your text?: "))
        text = input("Text: ")
        insert_num(line,text)
    elif command == 2:
        line = int(input("What line do you wish to delete?: "))
        delete_num(line)
    elif command == 3:
        line = int(input("What line do you wish to print?: "))
    elif command == 4:
        break
    else:
        print("invalid input, please select one of the following numbers:")

A: In your main loop, you call insert_num(line, text). But text here is the text string you inputted above, not the global variable text which is an instance of your LinkedList class. As the error says, strings don't have an insert method (because they are immutable).

A: You call these two lines
text = input("Text: ")
insert_num(line,text)

The resulting text variable will be type str, not a linked list. Strings do not have an insert, as the error is telling you.
And when you call these two lines:
import LinkedList
text= LinkedList.List()

That is a different text variable than the one that exists within the scope of your insert_num function.

A: The problem is variable scoping. When you call your insert_num() procedure you want to insert your new line (the text parameter, which is of type str) into your LinkedList of lines, which is also called text but because the method has a parameter with the same name, this (the linked list) is outside of the scope, and so can't be seen by the procedure.
text= LinkedList.List()

def insert_num(line,text):
    text.insert(line - 1,text)

I'd rename the subroutine's parameter:
text= LinkedList.List()

def insert_num(line_number, new_line):
    text.insert(line_number - 1,new_line)

A: .insert() Method can be used with list only, but you are trying to use it with a string. That is why you are getting error


text:
Q: python related plugins give errors in vim So here's an example of a vim plugin having python issues:
Error detected while processing function UltiSnipsEdit:
line    6:
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\2c.2c2c\.vim\bundle\ultisnips\plugin\UltiSnips\__init__.py", line 981, in file_to_edit
    os.mkdir(path)
WindowsError: [Error 3] The system cannot find the path specified: u'C:\\Users\\2c.2c2c\\vimfiles\\UltiSnips'
line   16:
E121: Undefined variable: file
E15: Invalid expression: ':'.mode.' '.file

Errors similar to this from vim plugin makers all say this is an issue with your python environment. I have the latest 27x and 3xx builds of python and use a precompiled vim from http://tuxproject.de/projects/vim/. I've uninstalled/reinstalled one or the other version, installed both versions, both with and without paths set. Nothing seems to have an effect.

:version

returns python/dyn for both versions, although I've messed with changing paths/uninstalling-reinstalling to have them alone and not alone etc. To see if anything changes. Also, basic python appears to actually work, I can do

:python print ("hello")

with no issue.
I'm also kind of confused why it's checking that directory... Vundle adds rtps to ~/.vim/bundle/addon for anything it installs.
Anyways, I haven't seen anyone with an issue like this on Windows, so none of the information is very helpful. Any help is appreciated.

A: The error originates from the function files_to_edit() in file "C:\Users\2c.2c2c.vim\bundle\ultisnips\plugin\UltiSnips__init__.py". Given a filetype (e.g, "markdown") this function tries figure out where the file with corresponding snippets ("markdown.snippets") might be located in your system. The function checks several places:

*

*If global variable g:UltiSnipsSnippetsDir exists, then it looks in that folder

*If global variable g:UltiSnipsSnippetDirectories exists, then it iterates over the items in rtp, appends the directory from the variable, and looks in the resulting folders

*If none of the above is set, then it iterates over the items in rtp, appends "UltiSnips" , and looks in the resulting folders

According to your error message

WindowsError: [Error 3] The system cannot find the path specified:
  u'C:\Users\2c.2c2c\vimfiles\UltiSnips'

it ended up in the third option. For some reason, it did not pick up the correct item from rtp. What you could do to fix the problem without digging into the plugin source code and debugging it is set g:UltiSnipsSnippetsDir explicitly to the location where the snippets are stored, i.e. "C:\Users\2c.2c2c.vim\bundle\ultisnips\UltiSnips". Just drop the line
let g:UltiSnipsSnippetsDir = "C:\Users\2c.2c2c\.vim\bundle\ultisnips\UltiSnips"

somewhere in your .vimrc.


text:
Q: image download: memory leak using LazyList I've got memory leak using LazyList.
I use one instance of ImageLoader in whole app, I create it in Application.onCreate(), because I need image downloading in several activities: list activity, one activity with gallery widget and full-screen gallery activitiy(all of them use same cache)
I modified image loader so it uses SoftReference-based HashMap. Here's code for SoftHashMap:
public class SoftHashMap extends AbstractMap {

    private final Map hash=new HashMap();
    private final int HARD_SIZE;
    private final LinkedList hardCache=new LinkedList();
    private final ReferenceQueue queue=new ReferenceQueue();

    public SoftHashMap(){
        this(100);
    }

    public SoftHashMap(int hardSize){
        HARD_SIZE=hardSize;
    }

    public Object get(Object key){
        Object result=null;
        SoftReference soft_ref=(SoftReference)hash.get(key);
        if(soft_ref!=null){
            result=soft_ref.get();
            if(result==null){
                hash.remove(key);
            }else{
                hardCache.addFirst(result);
                if(hardCache.size()>HARD_SIZE){
                    hardCache.removeLast();
                }
            }
        }
        return result;
    }
    private static class SoftValue extends SoftReference{
        private final Object key;
        public SoftValue(Object k, Object key, ReferenceQueue q) {
            super(k, q);
            this.key=key;
        }
    }

    private void processQueue(){
        SoftValue sv;
        while((sv=(SoftValue)queue.poll())!=null){
            hash.remove(sv.key);
       }
    }

    public Object put(Object key, Object value){
        processQueue();
        return hash.put(key, new SoftValue(value, key, queue));
    }

    public void clear(){
        hardCache.clear();
        processQueue();
        hash.clear();
    }

    public int size(){
        processQueue();
        return hash.size();
    }

    public Set entrySet() {
        throw new UnsupportedOperationException();
    }

}

ImageLoader class:
public class ImageLoader {

     private SoftHashMap cache=new SoftHashMap(15);

     private File cacheDir;
     final int stub_id=R.drawable.stub;
     private int mWidth, mHeight;

     public ImageLoader(Context context, int h, int w){
         mWidth=w;
         mHeight=h;

         photoLoaderThread.setPriority(Thread.NORM_PRIORITY);
         if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
                cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"CacheDir");
            else
                cacheDir=context.getCacheDir();
            if(!cacheDir.exists())
                cacheDir.mkdirs();
     }
     public void DisplayImage(String url, Activity activity, ImageView imageView)
        {

           Log.d("IMAGE LOADER", "getNativeHeapSize()-"+String.valueOf(Debug.getNativeHeapSize()/1024)+" kb");
           Log.d("IMAGE LOADER", "getNativeHeapAllocatedSize()-"+String.valueOf(Debug.getNativeHeapAllocatedSize()/1024)+" kb");
           Log.d("IMAGE LOADER", "getNativeHeapFreeSize()-"+String.valueOf(Debug.getNativeHeapFreeSize()/1024)+" kb");
           if(cache.get(url)!=null){
               imageView.setImageBitmap((Bitmap)cache.get(url));
           }
            else
            {
                queuePhoto(url, activity, imageView);
                imageView.setImageResource(stub_id);
            }
        }

        private void queuePhoto(String url, Activity activity, ImageView imageView)
        {
            //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them.
            photosQueue.Clean(imageView);
            PhotoToLoad p=new PhotoToLoad(url, imageView);
            synchronized(photosQueue.photosToLoad){
                photosQueue.photosToLoad.push(p);
                photosQueue.photosToLoad.notifyAll();
            }

            //start thread if it's not started yet
            if(photoLoaderThread.getState()==Thread.State.NEW)
                photoLoaderThread.start();
        }
     private Bitmap getBitmap(String url)
        {
            //I identify images by hashcode. Not a perfect solution, good for the demo.
            String filename=String.valueOf(url.hashCode());
            File f=new File(cacheDir, filename);

            //from SD cache
            Bitmap b = decodeFile(f);
            if(b!=null)
                return b;

            //from web
            try {
                Bitmap bitmap=null;
                InputStream is=new URL(url).openStream();
                OutputStream os = new FileOutputStream(f);
                Utils.CopyStream(is, os);
                os.close();
                bitmap = decodeFile(f);
                return bitmap;
            } catch (Exception ex){
               ex.printStackTrace();
               return null;
            }
        }

        //decodes image and scales it to reduce memory consumption
        private Bitmap decodeFile(File f){
            Bitmap b=null;
            try {
                //decode image size

                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                FileInputStream fis=new FileInputStream(f);
                BitmapFactory.decodeStream(fis,null,o);
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                //Find the correct scale value. It should be the power of 2.
                //final int REQUIRED_SIZE=mWidth;
                int width_tmp=o.outWidth, height_tmp=o.outHeight;
                int scale=1;

                while(true){
                    if(width_tmp/2<=mWidth || height_tmp/2<=mHeight)
                        break;
                    width_tmp/=2;
                    height_tmp/=2;
                    scale*=2;
                }

                //decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize=scale;
                //o2.inPurgeable=true;
                fis=new FileInputStream(f);
                b=BitmapFactory.decodeStream(fis, null, o2);
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return b;
            } catch (FileNotFoundException e) {}
            return null;
        }
     class PhotoToLoad{
         public String url;
         public ImageView imageView;

         public PhotoToLoad(String u, ImageView i){
             url=u;
             imageView=i;
         }
     }
     PhotosQueue photosQueue=new PhotosQueue();

        public void stopThread()
        {
            photoLoaderThread.interrupt();
        }
     class PhotosQueue{
         private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>();

         public void Clean(ImageView image)
            {
                for(int j=0 ;j<photosToLoad.size();){
                    if(photosToLoad.get(j).imageView==image)
                        photosToLoad.remove(j);
                    else
                        ++j;
                }
            }
     }
     class PhotosLoader extends Thread{
         public void run(){
             try {
                while(true)
                    {
                        //thread waits until there are any images to load in the queue
                        if(photosQueue.photosToLoad.size()==0)
                            synchronized(photosQueue.photosToLoad){
                                photosQueue.photosToLoad.wait();
                            }
                        if(photosQueue.photosToLoad.size()!=0)
                        {
                            PhotoToLoad photoToLoad;
                            synchronized(photosQueue.photosToLoad){
                                photoToLoad=photosQueue.photosToLoad.pop();
                            }
                            Bitmap bmp=getBitmap(photoToLoad.url);
                            cache.put(photoToLoad.url, bmp);
                            Object tag=photoToLoad.imageView.getTag();
                            if(tag!=null && ((String)tag).equals(photoToLoad.url)){
                                BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView);
                                Activity a=(Activity)photoToLoad.imageView.getContext();
                                a.runOnUiThread(bd);
                            }
                        }
                        if(Thread.interrupted())
                            break;
                    }
                } catch (InterruptedException e) {
                    //allow thread to exit
                }
         }
     }
     PhotosLoader photoLoaderThread=new PhotosLoader();

     class BitmapDisplayer implements Runnable
        {
            Bitmap bitmap;
            ImageView imageView;
            public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;}
            public void run()
            {
                if(bitmap!=null)
                    imageView.setImageBitmap(bitmap);
                else
                    imageView.setImageResource(stub_id);
            }
        }

        public void clearCache() {
            //clear memory cache
            cache.clear();

            //clear SD cache
            File[] files=cacheDir.listFiles();
            for(File f:files)
                f.delete();
        }
}

And my Application class, not the best way to do it, though:
public class MyApplication extends Application {

    ImageLoader mImageLoader;

    @Override
    public void onCreate(){

        int h =((WindowManager)getApplicationContext().getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getHeight();

        int w =((WindowManager)getApplicationContext().getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getWidth();
        mImageLoader=new ImageLoader(getApplicationContext(), h, w);
        super.onCreate();

    public ImageLoader getImageLoader(){
        return mImageLoader;
    }

    @Override
    public void onLowMemory(){
        mImageLoader.clearCache();
        Log.d("MY APP", "ON LOW MEMORY");
        super.onLowMemory();
    }
}

And the worst part: after some time I receive OOM exception when ImageLoader tries to decode another bitmap.
I'll appreciate any your help. Thanks.
EDIT I've got rid of hard cache, but i still get this OOM exception. It seems to me that I'm doing smth funny. I don't even know what extra information should I provide...
The images which i download from server are pretty big, though. And app fails to allocate appr. 1.5 mb, that's what I see in LogCat. But I just can't figure out why doesn't vm clear my SoftHashMap if there is need for memory...

A: *

*onLowMemory will be of no help to you as it is not generated when your app is running out of memory, it is called when the Android system would like memory for a different application or itself before it kills off processes.

*I don't see the need for hard cache - this is preventing drawables from being recycled. Just leave the drawables in the soft cache - the GC won't collect the memory while the drawables have references that are not soft so you don't need to worry about a drawable currently set in an ImageView being recycled.

Also how many images are you displaying on screen at once? How large are they?

A: *

*Here's an amazing article on analyzing memory leaks. It can definitely help you. http://android-developers.blogspot.com/2011/03/memory-analysis-for-android.html.

*Are you absolutely sure your SoftHashMap implementation works fine? Looks rather complicated. You can use debugger to ensure SoftHashMap never holds more than 15 bitmaps. MAT can also help you to identify how many bitmaps are there in memory.
You can also comment cache.put(photoToLoad.url, bmp) call. This way you'll disable in-memory caching to identify if it's a cause of a problem or not.

*Yes it may be an Activity leak. You can identify that. If you just scroll around in the same activity and get OOM it means that something else is leaking not activity. If you stop/start activity several times and get OOM it means activity is leaking.
Also you can definitely say is activity leaking or not if you take a look at MAT histogram.

*As you use inSampleSize the image size doesn't matter. It should work fine even with 5mpx images.

*You could try to replace your SoftHashMap implementation with just HashMap<String, SoftReference<Bitmap>>. Read about SoftReference. It is good for very simple implementation of in-memory cache. It holds objects in memory if there's enough memory. If there's too little memory SoftReference releases objects.

*I can also recommend you to use LinkedHashMap for in-memory cache. It has a special constuctor to iterate items in the order in which its entries were last accessed. So when you have more than 15 items in cache you can remove least-recently accessed items. As documentation says:

This kind of map is well-suited to building LRU caches.

*You know my implementation was designed with small images in mind, something like 50*50. If you have larger images you should think how much memory they consume. If they take too much you could just cache them to SD card but not to memory. The performance may be slower but OOM would not be a problem any more.

*Not related to OOM. I can see you call clearCache() in onLowMemory(). Not good because clearCache() also removes cache from SD. You should only clear in-memory cache not SD cache.

A: It looks like you're creating bitmaps, but never calling Bitmap.recycle().
EDIT:  To elaborate, Bitmap.recycle() frees memory currently being used to store the Bitmap.  Since Bitmaps created by the BitmapFactory are immutable, (you can check this with Bitmap.isMutable() on your freshly created bitmaps), simply removing a reference to them from the hashtable and waiting on the garbage collector isn't enough to free up the memory.
Call Bitmap Recycle whenever you're done with a specific bitmap (such as in the "clean" method of your photoQueue, or clearCache()).

A: I seen that below line is commented in your code, First of All uncomment that line plz.
//o2.inPurgeable=true;

In the NonPurgeable case, an encoded bitstream is decoded to a different Bitmap over and over again   until out-of-memory occurs. In Purgeable case, The memory allocated by one image will be shared by any new image whenever required and later any time if the older image reference is activiated in that case the OS will manage the memory reference it self by using a space of another image and vice verce and this way it always avoid the out of memory error.
If even you have purgeable case and still facing that memory leak then now use below try catch blog to trace the error and let me know the Stack Trace Detail.
    try{
    //your code to download or decode image
    }catch(Error e){
    //Print the stack trace
}


text:
Q: Quickly jumping to related-list on VF page The standard pages have menus at the top that allow you to quickly jump to the related lists further down on the page. Can we add these to our VF pages? I am using standard controller and using apex:detail tag.

A: There is no 'supported' way of displaying these hover links on custom (VF) detail pages just yet.
Here is an idea for it, which is surprisingly unpopular. I would've thought it would have a lot more votes.
http://success.salesforce.com/ideaView?id=08730000000ZQo4AAG
However, there are hacks, (which I haven't tried) where the JavaScript from page source has been used to render these sections on custom pages. http://boards.developerforce.com/t5/Visualforce-Development/Hoverlinks-for-custom-related-list/m-p/116812

A: Sorry guys, I am answering my own question. Hope it might be useful.
I developed following javascript code to generate similar links.
<apex:component >

<apex:includeScript value="{!URLFOR($Resource.JqueryUI, '/js/jquery-1.6.2.min.js')}" />


text:
Q: Electron: How do I communicate with browser window? In Electron, I have the below script is my main.js, it's a shortcut that restores the window and focuses it, however I want to focus an input inside the window. How do I achieve that?
main.js
app.on('ready', function(){
  createWindow();
  var ret = globalShortcut.register('Command+Control+Alt+G', function() {
    mainWindow.restore();
    mainWindow.focus();
    $('.js-search').focus();
  });
})

A: You could send a message from your main process to the renderer process using webContents, upon page focus.
The page (renderer process) can listen for that message and then focus the element itself.
Main process
globalShortcut.register('Command+Control+Alt+G', function() {

    win.restore();
    win.focus();
    win.webContents.send('focus-element', '.js-search');
});

Renderer process (the page)
<script>
    const {ipcRenderer} = require('electron');

    ipcRenderer.on('focus-element', (event, selector) => {
        document.querySelector(selector).focus();
    });
</script>


text:
Q: Summarising MONTH value I have a simple statement that starts:
SELECT a.product, MONTH(a.saledate) AS Month, Count(*) AS Total

Which yields, for example,
Product          Month        Total

Bike               8               1000

Please can anyone advise if it's possible to add the month's name to this query and also, is it possible to get a monthly total to appear as well?
Thanks!

A: There are two ways of getting month name
1)
SUBSTRING('JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ', (MONTH(a.saledate) * 4) - 3, 3)

2)
DATENAME(month, a.saledate)

Some poeple say You might be using MYSQL:
Then getting month name will be:
SELECT MONTHNAME( a.saledate);

A: The query in your example counts all the rows in your table, then presents that count next to a randomly chosen row's product and sale date. That's -- almost certainly -- not what you want.  MySQL is quirky that way. Other DBMSs reject your example query.
If you want to display a monthly summary of product sold, here's the basic query:
 SELECT a.product,
        LAST_DAY(a.saledate) AS month_ending,
        COUNT(*) AS Total
   FROM table a
  GROUP BY a.product, LAST_DAY(a.saledate)

The LAST_DAY() function is a great way to extract month and year from a date.
Finally, if you want to display the text name of the month, you can use the DATE_FORMAT() function to do that. %b as a format specifier gives a three-letter month name, and %M gives the full month name. So this query will do it.
 SELECT a.product,
        LAST_DAY(a.saledate) AS month_ending,
        DATE_FORMAT(LAST_DAY(a.saledate), '%M %Y')) AS month
        COUNT(*) AS Total
   FROM table a
  GROUP BY a.product, LAST_DAY(a.saledate)

In SQL Server 2012+ you can use the EOMONTH() function in place of LAST_DAY().
In SQL Server 2008+ you can use DATENAME(mm, a.saledate) to retrieve the month name from a date.


text:
Q: Update many records by id i'm woking with mongoose on a project and i have the following issue:
I need to update many records by its ids ( these ids was stored in an array ), i've tried this method:
 Collection.update({$in:{"_id":ids}}, {$set:{data_of_id}}, {upsert : true},
                 {"multi": true}, function(err, res){

                if(err){ console.log(err) };
                console.log(res);
 });

ids[] is the ids of the collection i need to update, and data_of_id is the new records wich will replace the old records. But i don't know how to associate these ids with each record in the array. I tried to put the update query into a foreach method too, but no success. The query above don't return any error or message, the called method was executed but don't execute the query.

A: The $in syntax is incorrect, it should be:
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

So, you should write it like this:
Collection.update({_id: {$in: ids}}, ...);

A: I've solved doing by this way:
        datas.forEach(function(data){

            Collection.update({"_id":data._id},
                data, {upsert : true},{new : true}, function(err, res){
                if(err) console.log(err);
            });

        });


text:
Q: Do I still need to include testflightlib in my iOS app? Now Apple have moved TestFlight to iTunes Connect do I still need to include testflightlib and call [TestFlight takeOff] on start with my app token? The new instructions don't mention this.
Additional question: Should I also keep using Crashlytics or is it redundant now?

A: You don't need to include your testflight lib and you don't need to call takeOff.
Actually, apple is already warning people to remove the framework from the projects.
Regarding crashlytics, yes, you should keep it for crashes since Apple still doesn't provide embedded crash reporting with test flight.
For more information about TestFlight read this excellent article.

A: You don't need to do anything like this anymore
The only step you need is to upload to iTunes Connect :)


text:
Q: ¿Como puedo solucionar el error de un metodo polimorfico cuando en una clase hijo funciona bien y en la otra no? El error que me sale es el siguiente System.NullReferenceException: 'Object reference not set to an instance of an object.'
La duda que tengo es en donde me estoy equivocando.
Clase padre con el método:
public abstract void Pagar_cuota(double valor, double cuotas);

Clase hijo#1 con el método:
public override void Pagar_cuota(double valor, double cuotas)
{
   valor = valor + (valor * 0.015);
   ValorCuota = valor;
}

Clase hijo#2 con el metodo:
public override void Pagar_cuota(double valor, double cuotas)
{
   valor = (valor+(valor * 0.2553)) / cuotas;
   ValorCuota = valor;
}

Invocacion del método a la clase main:
//Aquí cuando invoco el método con el segundo hijo me sale el error de
//la pregunta, pero si lo invoco por ejemplo
//hipotecario.Pagar_cuota(monto_cuota, cuotas); funciona correctamente

libreinversion.Pagar_cuota(monto_cuota, cuotas);

Console.WriteLine("El valor de cada cuota es: " + libreinversion.ValorCuota);

libreinversion.Valor = libreinversion.Valor -
libreinversion.ValorCuota;

Console.WriteLine("El valor es: " + libreinversion.Valor);


text:
Q: What is the difference between \eqref and \ref? Is there any difference between \eqref and \ref? I used both of them in my document using the package classicthesis and saw no difference in the result. Is there any specific situation in which I should use \eqref or \ref?

A: The command \ref is defined in the LaTeX Kernel. The command \eqref is defined by amsmath. In the documentation of amsmath you will find the explanation in section 3.11.2 Cross references to equation numbers.
\eqref puts brackets around the reference number. It's also places the references in in \upshape (or \textup), to match the equation reference exactly (Thanks to Werner). This is shown in the example below.
\documentclass{article}
\usepackage{amsmath}

\begin{document}
\begin{equation}
a^2+b^2=c^2\label{eq:1}
\end{equation}

\verb+\eqref{eq:1} vs \ref{eq:1}+: \eqref{eq:1} vs \ref{eq:1}

\verb+\textit{\eqref{eq:1} vs \ref{eq:1}}+: \textit{\eqref{eq:1} vs \ref{eq:1}}

\end{document}

If you use the package classicthesis, you must load amsmath before. Because the package classicthesis loads the package hyperref. However the package itself doesn't change the format of the output.


text:
Q: Is it possible to test AWS Lambda functions written in C# locally? I've started to learn about AWS Lambda and I've written a simple lambda function. I'd like to know if is it possible to test the DLL locally.
For example, for NodeJS, we can use the NPM package called "lamda-local", which I'm not very familiar with it.
I've seen that SAM Local only allows NodeJS, Java and Python runtime.
I'd like to know if there's a way to do the same with a Lambda function written in C#. Maybe I'm missunderstanding the concept of "testing the lambda function locally". I think that that means to test the AWS Lambda function in an emulated environment on our local machine, without "touching" the real AWS Console. Is that correct?
I could try creating a simple Console application to import the DLLs there, but I'm not sure if that's the correct way to do it.
Please, provide me with any other information that could be useful.
Thanks in advance.

A: Here is how we test our Lambda,
Create a machine from AMI as mentioned here,
https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html
Run your code on that machine. This is very much needed if you have any native libraries associated with your code.
Run your C# code with the version mentioned, .NET Core – .NET Core 1.0.1 (C#)
Once everything looks good, the code works in production lambda as well.
Hope it helps.

A: One can debug a lambda function locally using The AWS .NET Mock Lambda Test Tool.
This tool comes inbuilt with AWS Toolkit for Visual Studio.
After installing the tool and configuring your AWS profile, click on F5 to start debugging the function. You can invoke the lambda by clicking on Execute Function after inserting appropriate input payload.


text:
Q: Notepad++ Selectively delete lines within a file I have a dual .srt file that looks like this:
1
00:07:14,120 --> 00:07:16,953
[French line]
[Russian line]

2
00:07:16,960 --> 00:07:19,952
[French line]
[Russian line]

3
00:07:21,240 --> 00:07:24,835
[French line]
[Russian line]

I would like to delete all the Russian lines (plus the corresponding CRLF's). Which means lines 4, 9, 14, 19, 24, 29, and so on. It's every 5 lines, starting at line 4.
I guess Notepad++'s "Find in files" should be able to do it with the right RegEx (but I'm open to any solution). Could you please help me with that? Thank you.

A: To target every nth line in non empty line sequences:
(?:(?:\R|\A).+){3}\K\R.+

See this demo at regex101 (explanation on right side)

*

*\A matches start of the string

*\R matches any newline sequence

*\K resets beginning of the reported match

*.+ matches one or more of any character (besides newline)

*(?: non capturing group ) {3} quantified three times

Click on "replace all" and replace with empty.
Make sure to uncheck [ ] dot matches newline in the replace dialogue.
A bit more efficient alternative with atomic group: (?>\R?.+){3}\K\R.+


text:
Q: Node.js - Any way to Recover a Saved-Over Script that is Currently Running? I've accidentally saved over an existing node.js script-file making it completely blank on the file system. I'm not using any type of version control, so this long script file seems unrecoverable.
However, the app is currently running via pm2 (because it was started before I made this mistake).
Is there any way to recover this file from the running app via the node.js command prompt?


text:
Q: aspectj pointcut expression doing an or give inconsistent binding I have the following
@Pointcut("execution(* com.foo..*.*(..))")
public void logExecTimeAllMethods() {
}

//intercept all methods that are annotated with @LogExecTime
@Pointcut("@annotation(logExecTime)")
public void logExecTimeAnnotatedMethods(LogExecTime logExecTime) {
}

//add advice to above interceptors
@Around("logExecTimeAnnotatedMethods(logExecTime) || logExecTimeAllMethods()")
public Object logExecTime(ProceedingJoinPoint joinPoint, LogExecTime logExecTime) throws Throwable {

in the logExecTime If i replace the || with && it compiles file but with || I get "inconsistent binding"

A: You are accessing the annotation. That is only possible if it is present, which it doesn't have to if you use an OR-construct. If it's only a marker, you won't need it in the advice. If it contains valuable information you intend to use, you should handle that case in it's own advice.


text:
Q: How to sort a Numbers table using Javascript for Automation I want to sort a Numbers table using Javascript for Automation, the code like
table.sort(table.columns["P"], {direction: "descending"})

But the Script Editor told me: Parameter is missing. (-1701)

Here is the code I wrote:
 var Numbers = Application("Numbers")
 var path = Path("/Volumes/sfufoet/test.numbers")

 var doc = Numbers.open(path)

 var sheet = doc.sheets[1]
 var table = sheet.tables[1]

 table.sort(table.columns["P"], {direction: "descending"})

Thanks!

A: I found it!
the right code is:
table.sort({by:table.columns["P"], direction: "descending"})


text:
Q: How to parse a string that looks like JSON with lots of embedded classes in python? I have a string that lists the properties of a request event.
My string looks like:
requestBody: {
    propertyA = 1
    propertyB = 2
    propertyC = {
        propertyC1 = 1
        propertyC2 = 2
    }
    propertyD = [
        { propertyD1 = { propertyD11 = 1}},
        { propertyD1 = [ {propertyD21 = 1, propertyD22 = 2},
                         {propertyD21 = 3, propertyD22 = 4}]}
    ]
}

I have tried to replace the "=" with ":" so that I can put it into a JSON reader in python, but JSON also requires that key and value are stored in string with double quotes and a "," to separate each KV pair. This then became a little complicated to implement. What are some better approaches to parsing this into python dictionary with exactly the same structure (e.g. embedded dictionaries are also preserved)?
Question:
If I were to write a full parser, what's the main pattern that I should tackle? Storing parenthesis in a stack until the parenthesis completes?

A: This is a nice case for using pyparsing, especially since it adds the issue of recursive structuring.
The short answer is the following parser (processes everything after the leading requestBody :):
LBRACE,RBRACE,LBRACK,RBRACK,EQ = map(Suppress, "{}[]=")
NL = LineEnd().setName("NL")

# define special delimiter for lists and objects, since they can be
# comma-separated or just newline-separated
list_delim = NL | ','
list_delim.leaveWhitespace()

# use a parse action to convert numeric values to ints or floats at parse time
def convert_number(t):
    try:
        return int(t[0])
    except ValueError:
        return float(t[0])
number = Word(nums, nums+'.').addParseAction(convert_number)

qs = quotedString

# forward-declare value, since it will be defined recursively
obj_value = Forward()

ident = Word(alphas, alphanums+'_')
obj_property = Group(ident + EQ + obj_value)

# use Dict wrapper to auto-define nested properties as key-values
obj = Group(LBRACE + Dict(Optional(delimitedList(obj_property, delim=list_delim))) + RBRACE)

obj_array = Group(LBRACK + Optional(delimitedList(obj, delim=list_delim)) + RBRACK)

# now assign to previously-declared obj_value, using '<<=' operator
obj_value <<= obj_array | obj | number | qs

# parse the data
res = obj.parseString(sample)[0]

# convert the result to a dict
import pprint
pprint.pprint(res.asDict())

gives
{'propertyA': 1,
 'propertyB': 2,
 'propertyC': {'propertyC1': 1, 'propertyC2': 2},
 'propertyD': {'propertyD1': {'propertyD11': 1},
               'propertyD2': {'propertyD21': 3, 'propertyD22': 4}}}


text:
Q: ipad simulator rotating I am testing an application on iPad Simulator and I need it to start my app in the position the simulator is but every time I run the app, the simulator rotates to portrait.
Is there a way to stop this behavior?
thanks.
= = = =
last time edit: I discovered now that if I return NO on shouldAutorotateToInterfaceOrientation, the problem stops. But this is insane because shouldAutorotateToInterfaceOrientation should rotate the interface to match the iPad position, not the contrary.

A: I had this problem when running the GHUnit test app in the simulator. I fixed it by adding this to the info.plist file:
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
  <string>UIInterfaceOrientationPortrait</string>
  <string>UIInterfaceOrientationPortraitUpsideDown</string>
  <string>UIInterfaceOrientationLandscapeLeft</string>
  <string>UIInterfaceOrientationLandscapeRight</string>
</array>

If you edit this using Xcode's plist editor, make sure you have the "Show Raw Keys/Values" option turned on.

A: The iPad supports multiple launch images (as opposed to the iPhones singular default.png) so that an application can be launched in all rotations. Specifics here
I'm guessing that you are missing the new ones (default-landscape.png etc) so that when the application loads it can only find the portrait loading screen and therefor triggers a rotation (and the simulator responds by rotating to portrait). When you have shouldAutorotateToInterfaceOrientation return NO, it still can't find a landscape image but doesn't allow the rotation to take affect?

A: Once put in Landscape the sim stays in Landscape as long as you don't quit the simulator.  You can rerun your app and it will start in Landscape (well, except internally it is initially in portrait).

A: haven't tried it before... but maybe if you change the .plist file by adding

<key>UIInterfaceOrientation</key>
     <string>UIInterfaceOrientationPortrait</string>

I know it works on the iphone.

A: Just to comfirm, I agree with everything you say above Mike but you appear to maybe coming at it from the wrong angle.
One of the key points of the iPad (according to apple) is apps should be fully functionable in any orientation. If you read the apple speil on making the most of the additional iPad UI over the iPhone/iPod Touch, it goes into great details there.
If you use "cmd" + the left/right arrows you should be able to orientate the simulator. This will allow you to simulate exactly what a user would experience if they start your app in the wrong orientation from what you have coded.
I would recommend you reverse the code amendment you made(shouldAutorotateToInterfaceOrientation - NO) and code your app to display in any orientation. If you must code in just one then I suspect a user will be forced to rotate the device to rectify the issue.
I know you are keen to test your landscape app but I am unaware of any way the iPad Simulator can be forced to start in Landscape without you work around you mention above, which like you have already advised defeats the point. I suspect your stuck with "cmd" + "left/right" arrows.

A: I think I've got it!
If you close your simulator (like Cmd+Q), then it starts always in portrait mode.
But if you close your app by pressing the home button on the simulator, then it remembers the last orientation at the next start of your app.


text:
Q: Call AfxGetMainWnd() from derived class of DialogEx returns NULL I need to gain access to a member of main frame and can be changed by reference.
Here is a free function to get main frame
inline CMainFrame* GetMainFrame()
{
    CMainFrame* mainFrame = dynamic_cast<CMainFrame*>(AfxGetMainWnd());
    ASSERT(mainFrame);
    return mainFrame;
}

I called above function to my Dialog of an MFC application and found the main frame pointer NULL.
How can I gain access of main frame member which can be changed by reference?
Thanks in advance.


text:
Q: Is there a way to easily wrap or extend Angular-material directives in Angular 5? I am using the angular-material library here and there in an angular5 application, but I don't want its directive/component/class names in my markup, which I prefer to keep agnostic with respect to external libraries.  However, I tried doing something like this:
import { Directive,
         ElementRef,
         Renderer,
         Renderer2 }  from "@angular/core";

import { MatButton }  from "@angular/material";
import { OnInit }     from "@angular/core";
import { Platform}    from "@angular/cdk/platform";
import {FocusMonitor} from "@angular/cdk/a11y";

@Directive({
  selector: '[my-button]'
})
export class MyButtonDirective extends MatButton {

  ngOnInit(): void {

  }

  constructor(renderer: Renderer2, elementRef: ElementRef, _platform: Platform, _focusMonitor: FocusMonitor) {
    super(renderer, elementRef, _platform, _focusMonitor);

  }
}

But when I apply the my-button attribute, it seems to have no effect whatsoever.  Even console.logs from inside the directive constructor/onInit are not printed.  I'm not real sure what I'm doing wrong as I've never used directives before in Angular.

A: I don't know how much further you'd get, but you said you are using an attribute, when maybe you want to use an element Test

A: you are missing your template.
Extends only give access to your code but template is not automatically extended.
this is similar..when you create npm package for your component. You are required to export class and then template.


text:
Q: Convert NSString to FBSDKAccessToken Is there anyway to convert my NSString access token to type FBSDKAccessToken? I need it to be of this form to perform login with Facebook and Parse:
[PFFacebookUtils logInInBackgroundWithAccessToken:AccessToken
    block:^(PFUser *user, NSError *error) {
        if (!user) {
            NSLog(@"Uh oh. There was an error logging in.");
        } else {
            NSLog(@"User logged in through Facebook!");
            NSLog(@"%@", user);
        }
}];

A: If it is a simple login as you have in your example you shouldn't need to do it at all, and instead just call +currentAccessToken.
But if you actually want to create it, you can just initialize a new AccessToken and pass it in the request
- (instancetype)
initWithTokenString: (NSString *)tokenString
        permissions: (NSArray *)permissions
declinedPermissions: (NSArray *)declinedPermissions
              appID: (NSString *)appID
             userID: (NSString *)userID
     expirationDate: (NSDate *)expirationDate
        refreshDate: (NSDate *)refreshDate
                     NS_DESIGNATED_INITIALIZER;

This initializer should only be used for advanced apps that manage
  tokens explicitly. Typical login flows only need to use
  FBSDKLoginManager along with +currentAccessToken.

find more in the Facebook documentation.


text:
Q: Default value of Point type In Laravel migrations, what should I use as the default value of Point type column? I originally wanted to keep it NULL but then I read that:

Columns in spatial indexes must be declared NOT NULL.

So what should I use as the default value of my column and how do I specify that in migration, to represent NULL, something like 0,0 or -1,-1?
$table->point('location')->default(???);

UPDATE
Doing more research, I found an even bigger issue. MySQL doesn't allow specifying default value for POINT type column. So I must insert a NULL-equivalent at INSERT time. What would be the correct value for this purpose?

A: I don't know if it is you case, but if you are trying to add a column to an existing table, and then add a spatial index to that on a migration, the way I find to address this in MySQL was not an elegant solution, but worked:
Schema::table('table', function(Blueprint $table)
{
    // Add the new nullable column
    $table->point('column')->nullable();
});
// You must separate this to ensure the execution order
Schema::table('table', function(Blueprint $table)
{
    // Insert the dummy values on the column
    DB::statement("UPDATE `table` SET `column` = POINT(0,90);");
    // Set the column to not null
    DB::statement("ALTER TABLE `table` CHANGE `column` `column` POINT NOT NULL;");

    // Finally add the spatial index
    $table->spatialIndex('column');
});

A: Using MariaDB, I could insert it successfully with:
->default(DB::raw("POINT(0,90)"))


text:
Q: Elastic Search multiple ranges in PHP I have been staring at my monitor for too long not to ask: how do I perform multiple range queries using Elastic Search PHP library?
I am trying to query my index based on price criteria (less and more than) and product quantity within its category (minimum 2 products, 2 products only etc).
While $searchParams['body']['query']['range']['number_of_products'] = ['gte' => $products + 1];
 on its own works fine, combined with
$searchParams['body']['query']['range']['price'] = [
    'gte' => $price['min'],
    'lte' => $price['max'],
];

I am struggling to find a decent recent example covering this scenario post ES v0.9, which on my v1.4.2 fails.

A: Your answer is correct.  As an aside, performance will tend to be better if you use the bool filter rather than and/or/not set of filters.  It isn't always the case, but usually.
And/or/not works in a "leapfrog iterator" pattern.  This finds the first matching doc in the first filter, then attempts to "leapfrog" the rest of the filter iterators until they all align on the same doc.  This makes it efficient for sparse filters.
In contrast, the Bool filter does bitwise combination of bitmaps (representing matching docs), which tends to be more efficient for denser filters.  Your filters look relatively dense:

*

*The number_of_products filter is all values >= $products['min'], which could be a large number of matching docs...all in a contiguous range

*The density of price filter depends on the size of the range, but could also be quite dense (and contiguous).  If there is no $price['max'], it is also unbounded to infinity.

In practice, bool tends to give better performance than and/or/not, and probably will in this example, but YMMV. :)
$searchParams = [
    'index' => 'my_index',
    'type' => 'my_type',
    'body' => [
        'query' => [
            'filtered' => [
                'filter' => [
                    'bool' => [
                        'must' => [
                            [
                                'range' => [
                                    'number_of_products' => [
                                        'gte' => $products['min']
                                    ]
                                ]
                            ],
                            [
                                'range' => [
                                    'price' => [
                                        'gt' => $price['min'],
                                        'lt' => ($price['max'] ? : null)
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
];

A: Thanks to these articles:

*

*Elasticsearch: can't filter on multiple fields

*https://groups.google.com/forum/#!topic/elasticsearch/BainRz0LGIw

*http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-filtered-query.html

*http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/combining-filters.html

*How are filters applied in Elastic Search?
I finally came up with a working solution:
$searchParams['body']['query']['filtered']['filter']['and'][]['range']['number_of_products'] = ['gte' => $products['min']];
$searchParams['body']['query']['filtered']['filter']['and'][]['range']['price'] = [
            'gt' => $price['min'],
            'lt' => ($price['max'] ? : null),
        ];


text:
Q: How can I interpret my string content in WPF control? I have a string with a xaml code inside and I want to know how can I bind this content to a control like TextBlock or Label or other.
My string value is like this :
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:markdig="clr-namespace:Markdig.Wpf;assembly=Markdig.Wpf" Style="{StaticResource {x:Static markdig:Styles.DocumentStyleKey}}">
<Paragraph Style="{StaticResource {x:Static markdig:Styles.Heading1StyleKey}}">
    <Run Text="Changelog" />
</Paragraph>
<Paragraph>
    <Run Text="All notable changes to this project will be documented in this file." />
</Paragraph>

The program is returning exactly what I show you.
I hope some one can help me. Perhaps I just don't know how to explain my problem on google

A: I convert my string to Stream
        byte[] byteArray = Encoding.ASCII.GetBytes(ChangelogContent);
        MemoryStream stream = new MemoryStream(byteArray);
        scrollView.Content = XamlReader.Load(stream);


text:
Q: How to access $scope from $resource I need to splice an array on success.  How do I call back out to my $scope.list in order to remove an item from the list array?  Is that how I should do it or is there a better way?  Like bubbling an "update" or something?
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
    var urlBase = 'http://example.com/api/';

    function resourceErrorHandler(response) {

        console.log("error");
    }
    function resourceResponseHandler(response) {
        console.log($scope.list);

        $scope.list.data.splice(index, 1);
        console.log("success");
    }
    phonecatServices.factory('api_resource', ['$resource',
      function($resource){
        return $resource(urlBase+':api_resource/:id.json', {}, {
          query: {method:'GET', isArray:false},
          save:{method:'POST', isArray:false},
          delete:{method:'DELETE', isArray:false, interceptor:{response:resourceResponseHandler, responseError:resourceErrorHandler}},
         });
      }]);

A: Make $scope an argument in the functions and pass it with the method call in the controllers, or bundle it in the response object.


text:
Q: Write performance issues with SSD RAID 10 on P840/4gb fbwc I have a new system with 4x512GB Samsung SSD 850 in a RAID10 array using P840/4gb fbwc RAID controller. When i download a file from network (10 Gbit/s) write speed is not that good. I tried downloading a single 1000MB file using wget:
Saving to: '1000mb.bin'

1000mb.bin                                       100%[=========================================================================================================>]   1000M   383MB/s   in 2.6s

Write speed 383Mbyte/s
EDIT: When downloading the same file to /dev/null I get full 10Gbit/s speed. The use case is downloading and storing files of that size.
Also when i try to write a file using dd, speed is the same with block size 512byte:
dd if=/dev/zero of=bench.bin bs=512 count=10000K
10240000+0 records in
10240000+0 records out
5242880000 bytes (5.2 GB) copied, 14.6632 s, 358 MB/s

However block size 4k gives better performance:
dd if=/dev/zero of=bench.bin bs=4k count=1000K
1024000+0 records in
1024000+0 records out
4194304000 bytes (4.2 GB) copied, 3.02447 s, 1.4 GB/s

So i tried various different settings concerning cache, SSD smart path, etc. for the raid controller. But i didn't see much difference. Any ideas how to increase write speed?
Current settings for the controller:
Smart Array P840 in Slot 1
   Bus Interface: PCI
   Slot: 1
   Serial Number:
   Cache Serial Number:
   RAID 6 (ADG) Status: Enabled
   Controller Status: OK
   Hardware Revision: B
   Firmware Version: 4.52
   Rebuild Priority: High
   Expand Priority: Medium
   Surface Scan Delay: 3 secs
   Surface Scan Mode: Idle
   Parallel Surface Scan Supported: Yes
   Current Parallel Surface Scan Count: 1
   Max Parallel Surface Scan Count: 16
   Queue Depth: Automatic
   Monitor and Performance Delay: 60  min
   Elevator Sort: Enabled
   Degraded Performance Optimization: Disabled
   Inconsistency Repair Policy: Disabled
   Wait for Cache Room: Disabled
   Surface Analysis Inconsistency Notification: Disabled
   Post Prompt Timeout: 15 secs
   Cache Board Present: True
   Cache Status: OK
   Cache Ratio: 10% Read / 90% Write
   Drive Write Cache: Disabled
   Total Cache Size: 4.0 GB
   Total Cache Memory Available: 3.8 GB
   No-Battery Write Cache: Disabled
   SSD Caching RAID5 WriteBack Enabled: True
   SSD Caching Version: 2
   Cache Backup Power Source: Batteries
   Battery/Capacitor Count: 1
   Battery/Capacitor Status: OK
   SATA NCQ Supported: True
   Spare Activation Mode: Activate on physical drive failure (default)
   Controller Temperature (C): 44
   Cache Module Temperature (C): 37
   Number of Ports: 2 Internal only
   Encryption: Disabled
   Express Local Encryption: False
   Driver Name: hpsa
   Driver Version: 3.4.4
   Driver Supports HP SSD Smart Path: True
   PCI Address (Domain:Bus:Device.Function): 0000:06:00.0
   Negotiated PCIe Data Rate: PCIe 3.0 x8 (7880 MB/s)
   Controller Mode: RAID
   Controller Mode Reboot: Not Required
   Latency Scheduler Setting: Disabled
   Current Power Mode: MaxPerformance
   Host Serial Number:
   Sanitize Erase Supported: False
   Primary Boot Volume: logicaldrive 1
   Secondary Boot Volume: logicaldrive 2

Physical Drives
      physicaldrive 2I:1:1 (port 2I:box 1:bay 1, Solid State SATA, 512.1 GB, OK)
      physicaldrive 2I:1:2 (port 2I:box 1:bay 2, Solid State SATA, 512.1 GB, OK)
      physicaldrive 2I:1:3 (port 2I:box 1:bay 3, Solid State SATA, 512.1 GB, OK)
      physicaldrive 2I:1:4 (port 2I:box 1:bay 4, Solid State SATA, 512.1 GB, OK)
      None attached

   Array: A
      Interface Type: Solid State SATA
      Unused Space: 0  MB (0.0%)
      Used Space: 1.9 TB (100.0%)
      Status: OK
      MultiDomain Status: OK
      Array Type: Data
      HP SSD Smart Path: disable

      Logical Drive: 1
         Size: 953.8 GB
         Fault Tolerance: 1+0
         Heads: 255
         Sectors Per Track: 32
         Cylinders: 65535
         Strip Size: 256 KB
         Full Stripe Size: 512 KB
         Status: OK
         MultiDomain Status: OK
         Caching:  Enabled
         Unique Identifier:
         Disk Name: /dev/sda
         Mount Points: /boot 487 MB Partition Number 2, / 14.0 GB Partition Number 7
         OS Status: LOCKED
         Logical Drive Label:
         Mirror Group 1:
            physicaldrive 2I:1:1 (port 2I:box 1:bay 1, Solid State SATA, 512.1 GB, OK)
            physicaldrive 2I:1:2 (port 2I:box 1:bay 2, Solid State SATA, 512.1 GB, OK)
         Mirror Group 2:
            physicaldrive 2I:1:3 (port 2I:box 1:bay 3, Solid State SATA, 512.1 GB, OK)
            physicaldrive 2I:1:4 (port 2I:box 1:bay 4, Solid State SATA, 512.1 GB, OK)
         Drive Type: Data
         LD Acceleration Method: Controller Cache

Any help appreciated :)

UPDATE: We have reached Performance increase by switching from ext4 to xfs. Thanks to everyone who has answered.

A: I would recommend  to increase TagQue for disks to 256+. Anyway one should understand /dev/null do not require interrupt and physical IO to/from SmartArray does. In your example 380MB/s with 512B block size generates 778,240 IOps. SA840 can provide approx. 1M IO/s in benchmark configuration (24xSSD RAID0). Recapitulation: one should NOT expect high throughput if small block is in use - change  tool/setting to assure block 128kB+ are used to have performance up to 5GB/s on single SA840.


text:
Q: Drawing buildings with Holes inside with Openstreetmap XML data I'm trying to draw a map using OSM raw data.Some of buildings have holes inside (may even more than one hole at a time) .
In way list, all I can see is set of "way nodes". Where should I get the information in OSM.xml that a  Node represent a hole is belong to a specific building?
Note: In Relation there is innerWay - outerWay relation for some buildings but it does not cover all the cases as I see. How openstreetmap draw building?
I achieved drawing it in Opengl using tesselation without knowing which hole belong which building but, I couldn't apply same approach on unity. Here is a screenshot from opengl :

A: "Note: In Relation there is innerWay - outerWay relation for some buildings but it does not cover all the cases as I see. How openstreetmap draw building?"
The reason you are not seeing "all the cases" as you mentioned, is because the default OpenStreetMap Carto rendering actually kind of "hides" data errors: it simply stacks polygons in size-based order from large on the bottom, to small on top. This means that some of the apperent "inner-courts" or holes of buildings you see, aren't actual proper multipolygons with inner and outer roles defined for constituting ways, but simply a smaller polygon with a different landuse or so, stacked on top of a non-multipolygon building outline.
This means that if you do proper processing of the data and multipolygons (which you should IMO), and ignore this "visual" fix, then you will not get the same "pretty", but in essence false, picture that the default rendering presents to you.


text:
Q: Selecting folders, not files, in Google Chrome I'm creating an extension for Google Chrome, so any code has to be compatible with Chrome and Chrome only. In this extension, I need the user to select a folder from his local machine. This simple task is becoming quite a problem. The chrome extensions options page will not run applets, so I couldn't really do Java. It's Google Chrome only so an ActiveX object is out of the question as well. I just need a simple way of selecting a folder(not a file) and passing its path to Javascript. Might this be possible in Flash Actionscript? It seems FileReference and FileReferenceList classes in AS only allow you to choose a file, and not a folder. Is there another possibility besides Flash? All the options page files DO rest on the local users machine, so it's not server side.
Thank you for your time.

A: You can use the webkit-directory attribute on your  element to select directories and get the same sort of result as from the "multiple" attribute.
A demo of this: http://www.thecssninja.com/demo/webkitdirectory/
The chromium bug: http://crbug.com/58977


text:
Q: Room database: click on a record and open a new activity I have a Room database with customers. I start an activity where you see a list of the customers.
I want to click on a specific customer and start an activity, where I can see more details of the customer.
I know that you need to use the OnClickListener method if you want to click on a button and start a new activity. But here, my list is made with CardView.
How can I click on a customer and open a new activity? And how do I let the database give me the correct information of the correct customer, like: If I have a Peter in my list, how can I click on him and see more information about him? Do I need something like get(position) in a method to see the information connected to that customerID?

This is my list. Every card consists a customer in this list. But the cards are not buttons and they don't have a button.

A: Since this is a list of Customers you need a click listener, like this
interface CustomerClickListener {
    fun onCustomerClick(position:Int)
}

Which you will implement in your Activity and will pass to your Adapter:RecyclerView.Adapter. In the adapter call this listener when a item is clicked.
class CustomerHolder(listener:CustomerClickListener, view:View):RecyclerView.ViewHolder(view) {
    //...
    view.setOnClickListener { listener.onCustomerClick(adapterPosition) }
}

In you activity, which will implement CustomerClickListener, call second activity with the id of clicked Customer. Like this
override fun onCustomerClick(position:Int) {
    val id = customers[position].id ?: return
    CustomerInfoActivity.open(id)
}

Method CustomerInfoActivity.open(id) creates an intent that launches second activity and passed an id as an extra. In your second activity retrieve passed customer id from the intent and call database to get its info.
Updated with Java version
Create interface CustomerClickListener, which will be used to interact with recycler view items.
public interface CustomerClickListener {
    void onCustomerClick(int position);
}

Add this interface as a parameter to your Adapter constructor.
public class CustomersAdapter extends RecyclerView.Adapter<CustomerHolder> {
    private CustomerClickListener listener;

    public CustomersAdapter(CustomerClickListener listener) {
        this.listener = listener;
    }

    class CustomerHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private CustomerClickListener listener;

        CustomerHolder(View itemView, CustomerClickListener listener) {
            super(itemView);
            this.listener = listener;

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onCustomerClick(getAdapterPosition());
            }
        }
    }
}

Implement interface from above and pass it to the adapter. Like this:
public class MyActivity extends Activity implements CustomerClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        recyclerView = findViewById(R.id.recycler_view);
        CustomersAdapter adapter = new CustomersAdapter(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onCustomerClick(int position) {
        // Get customer based on the position from the customers list
        Customer customer = customers.get(position);
        CustomerInfoActivity.open(this, customer.getId());
    }
}

In the CustomerInfoActivity add this static method, which will add customer id to intent.
public static void open(Activity activity, long customerId) {
    Intent intent = new Intent(activity, CustomerInfoActivity.class);
    intent.putExtra("CustomerID", customerId);
    activity.startActivity(intent);
}

And in CustomerInfoActivity get passed customer id like this
public class CustomerInfoActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    //...
    Intent intent = getIntent();
    if (intent != null && intent.hasExtra("CustomerID")) {
        long customerId = intent.getLongExtra("CustomerID", -1);
        // TODO: get customer details based on customer id
    } else {
        // ...
    }
}

}

A: Use setOnItemClickListener() inside your listview to detect item clicked by user and pass relevant data to your activity through bundle, like below sample :
 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                     Intent intent = new Intent(RoomActivity.this, CustomerDetailActivity.class);
                     intent.putExtra(CUSTOMER_ID, listData.get(position).getId();
                     startActivity(intent);
  }
});

Hope it helps!


text:
Q: How to document only a subset of functions in Sphinx? Using Sphinx, I need to generate two sets of documentation for my Python app:

*

*Contains all my modules/functions

*Contains only a subset of functions from my modules

I want to use a "tag" in the function docstrings that would indicate whether or not to include the function in the 2nd set of documents.
With .. only, I'm able to control which part of the docstring gets included depending on -t <tagname> that I provide to sphinx-build. But I'm not able to find any way of filtering out a set of functions to be included in the scope of the documentation based on docstring entries of these functions.

A: As it usually happens - after posting question you come up with the answer.
Managed to achieve this using https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#skipping-members and putting following code to conf.py
def include_only_tagged(app, what, name, obj, skip, options):
    inclusion_tag_format = ".. only:: {}" #can be any pattern here, choose what works for you
    for tag in app.tags.tags:
        if obj.__doc__ is not None and inclusion_tag_format.format(tag) in obj.__doc__:
            return False
    return True

def setup(app):
    if(len(app.tags.tags)>0):
        app.connect('autodoc-skip-member', include_only_tagged)

So if I use something like ".. only:: subset" as part of my docstring for any function - that says that whenever I run sphinx-build -t subset only this function(s) will be kept in scope of generated documentation.


text:
Q: Understanding the time complexity of given code I was coding for a simple question on codeforces. It reads like this:
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?
Input
The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100), separated by a space.
Output
Print a single integer — the answer to the problem.
My solution is this :
int main()
{
    int res,i,n,m;
    cin >> n >> m;

    i = 1;
    res = n;
    while(res >= i*m)
    {
        res++;
        i++;
    }

    cout << res;
    return 0;
}

What should be the time complexity? Its definitely not O(n), as we are increasing in steps of m. Will it be log n (base m)? But also the original n increases with time !!!
Please put some justifications.

A: The biggest factor in the RAM computation model would be:
while(res >= i*m)
{
    res++;
    i++;
}

The bounding factor will be:
n + i < i*m since res starts at n and grows at the same rate as i
i*m-i > n
i > n / (m-1)
Since we are dealing with integer values here, an additional bound will be
i >= 1
The algorithm will grow with O(n/m)

A: it's a very nice coding...
to find time complexity we can ignore here the increment of n as m is chasing behind with multiples of increment on its own value like 1m,2m,3m,so we can ignore additional increments over multiple increments....so while loop will iterate here upto what multiples of m to overdo the value of n (ignoring n's increment)..
And complexity evidently O(n/m) .
And for the consecutive days dat the girl will be running out of sock u can print the value of (m*i-res)...


text:
Q: CodeIgniter unable to send email using PHP mail() I'm trying to send an e-mail with Codeigniter like this:
$this->load->library('email');

$this->email->from("myemail@email.com");
$this->email->reply_to("myemail@email.com");
$this->email->to("myemail@email.com");
$this->email->subject("Test mail");
$this->email->message("Email body");
$this->email->set_alt_message("Email body txt");
$this->email->send();

and I got this on the email debugger: Unable to send email using PHP mail().  Your server might not be configured to send mail using this method.
If I do e simple PHP mail() function with the same addresses, it works but when I use CodeIgniter it gives me the error. So why would it work with simple mail() but not with CodeIgniter ? Any ideas ?
Thanks.

A: Do you have an email.php file in your config folder? Maybe there's a problem with your configuration in there.

A: Nobody seemed to really find a definitive answer, so I did some digging around and found out why.
in system/libraries/Email.php, first look at line 1552:
if ( ! mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, "-f ".$this->clean_email($this->_headers['From'])))

it seems to send everything all peachy like.  I had the exact same symptoms too.  To see if I was crazy, i inserted immediately before...
mail($this->_recipients, $this->_subject, $this->_finalbody)

so I basically removed all the headers and let PHP put in the defaults.  Bingo!  Without CI's headers, it works.  With the CI headers, it doesn't.  So what is it?
Digging around some more, I looked up to where html is initialized and used.  Turns out it doesn't really do anything until around 1046, where it builds the message body.
from line 1048:
if ($this->send_multipart === FALSE)
{
    $hdr .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
    $hdr .= "Content-Transfer-Encoding: quoted-printable";
}
else
{
    $hdr .= "Content-Type: multipart/alternative; boundary=\"" . $this->_alt_boundary . "\"" . $this->newline . $this->newline;

    $body .= $this->_get_mime_message() . $this->newline . $this->newline;
    $body .= "--" . $this->_alt_boundary . $this->newline;

    $body .= "Content-Type: text/plain; charset=" . $this->charset . $this->newline;
    $body .= "Content-Transfer-Encoding: " . $this->_get_encoding() . $this->newline . $this->newline;
    $body .= $this->_get_alt_message() . $this->newline . $this->newline . "--" . $this->_alt_boundary . $this->newline;

    $body .= "Content-Type: text/html; charset=" . $this->charset . $this->newline;
    $body .= "Content-Transfer-Encoding: quoted-printable" . $this->newline . $this->newline;
}

Flipping send_multipart between TRUE and FALSE will make the mail class work or not work.
Looked through the Code Ignitor's email class docs reveals nothing.  Going to line 52:
var $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override.  Set to FALSE for Yahoo.

So there you have it.  Possibly an error in how CI does multipart messages?  The hidden config preference
$config['send_multipart'] = FALSE;

in the email.php seems to do the trick.

A: Be sure domain name in
$this->email->from("myemail@**email.com**");

match to server domain name

A: Add a protocol variable to the config array and assign it the value "sendmail". The email.php file in the config folder should read as shown below. Mine works like this:
$config['protocol'] = 'sendmail';
$config['mailtype'] = 'html';
$config['charset']  = 'utf-8';
$config['newline']  = "\r\n";

A: Ensure that Apache can send emails.
To check your current sendmail status:
sestatus -b | grep httpd_can_sendmail
Change it to this if it is off:
sudo setsebool -P httpd_can_sendmail on

A: Had similar issue.
That's working code from the controller :
        $config = array();
        $config['useragent']           = "CodeIgniter";
        $config['mailpath']            = "/usr/bin/sendmail"; // or "/usr/sbin/sendmail"
        $config['protocol']            = "smtp";
        $config['smtp_host']           = "localhost";
        $config['smtp_port']           = "25";
        $config['mailtype'] = 'html';
        $config['charset']  = 'utf-8';
        $config['newline']  = "\r\n";
        $config['wordwrap'] = TRUE;

        $this->load->library('email');

        $this->email->initialize($config);

        $this->email->from($fromEmail, $fromName);
        $this->email->to($email);

        $this->email->subject('Тест Email');
        $this->email->message($this->load->view('email/'.$type.'-html', $data, TRUE));

        $this->email->send();

A: Clearly, there does not seem to be a definitive 'one size fits all' answer. What worked for me was changing
$config['protocol'] = 'smtp';

TO:
$config['protocol'] = 'mail';

Hope this helps...

A: I read a comment in the file email.php :
// most documentation of sendmail using the "-f" flag lacks a space after it, however
        // we've encountered servers that seem to require it to be in place.
        return mail($this->_recipients, $this->_subject, $this->_finalbody, $this->_header_str, '-f '.$this->clean_email($this->_headers['Return-Path']));

"-f" flag - this problem!!!

A: Had the same problem,
Make sure your 'from' address is a valid email address.

A: I had the same problem and though it seems silly to me now, I had some of the config array options capitalized when they all need to be lowercase:
was:
$mail_config['smtp_host'] = 'mail.example.com';
$mail_config['smtp_port'] = '587';
$mail_config['smtp_user'] = 'email@example.com';
$mail_config['smtp_pass'] = 'password';
$mail_config['smtp_crypto'] = 'TLS'; //ERROR
$mail_config['protocol'] = 'SMTP'; //ERROR
$mail_config['mailtype'] = 'HTML'; //ERROR
$mail_config['send_multipart'] = FALSE;
$this->email->initialize($mail_config);

Fixed:
$mail_config['smtp_host'] = 'mail.example.com';
$mail_config['smtp_port'] = '587';
$mail_config['smtp_user'] = 'email@example.com';
$mail_config['smtp_pass'] = 'password';
$mail_config['smtp_crypto'] = 'tls'; //FIXED
$mail_config['protocol'] = 'smtp'; //FIXED
$mail_config['mailtype'] = 'html'; //FIXED
$mail_config['send_multipart'] = FALSE;
$this->email->initialize($mail_config);

That worked for me

A: Its worth saying that if you're on WAMP (Windows) you will need to have sendmail installed otherwise there is no default SMTP method of sending. I wanted to use Gmail but couldn't because there is simply no default mail mechanism.

A:     $config = Array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'email',
        'smtp_pass' => 'pass',
        'mailtype'  => 'html',
        'charset'   => 'iso-8859-1'
    );

    $this->load->library('email',$config);
**$this->email->set_newline("\r\n");**  <- add this line
   this code worked for me.


text:
Q: Is there a better way to get values out of a table row? Say I have this

<input type="checkbox" name="vehicle" value="Bike" />
row 1, cell 1
row 1, cell 2

<input type="checkbox" name="vehicle" value="Bike" />
row 2, cell 1
row 2, cell 2

Now I want to get the row that is checked, then the cell values of that checked row. So I would do this
 var cells = $('#tbl :checked').parents('tr').children('td');

So lets assume only one checkbox can be checked(so no jQuery foreach loop).
So now say I wanted to get the 2nd table cells value I would just go
var secondCell = $(cells[1]).html();

The thing with this though it makes the code so brittle. Like what if I put another table cell after after the checkbox one?

<input type="checkbox" name="vehicle" value="Bike" />
    I am new
  row 1, cell 1
  row 1, cell 2

<input type="checkbox" name="vehicle" value="Bike" />
    I am new
  row 2, cell 1
  row 2, cell 2

So now I have to go through my code and change this
var secondCell = $(cells[1]).html();

to  this
var thirdCell = $(cells[2]).html();

Since now I am actually after the 3rd cell and not the 2nd cell anymore.
So is there a better way?
Thanks

A: Give the tds of interest a classname so that you can select them using the classname selector.

    <input type="checkbox" name="vehicle" value="Bike" />
     I am new
    row 1, cell 1
    row 1, cell 2

with
var row = $('#tbl :checked').parents('tr');
var cell1 = $('.cell1', row);
var cell2 = $('.cell2', row);

You would probably also rather use text() to get its contents. The html() would return any the containing HTML as well which might not be of your interest.
Have you considered as well to use the <input type="radio"> to force a single selection? If you give them all the same name, then they belongs to the same single selection group.

A: I like the @BalusC answer and suggest you to use it but if for some reason you can not do that, why just don't use global constants?
var PRICE_ROW = 1;
var AMOUNT_ROW = 2;

$(cells[PRICE_ROW]).html();

Another alternative might include converting rows to JavaScript objects with names as keys before use.

A: I went through the same thing a few days ago, I have a table full of check boxes that I need to pull cell values from for client side evaluation.  Here is what I came up with.
// Find all the checked checkboxes in a table
var CheckedCheckBoxes = $('#tbl').find("input[type='checkbox']:checked");

// Loop over all the checked checkboxes, and pull in the value from the 'td' item I select
CheckedCheckBoxes.each(function() {
    var cellValue = $(this).parent().parent().find('td:eq(2)').text();
}

I'm pretty sure you'll need parent().parent() since the checkbox is in a td that is in a tr, and you need to get to the tr to search for the td (cell) you want.

A: In response to your comment to BalusC's answer...
If you are hiding the cells with extra information you need, then retrieving it with the above script. I think it would be more efficient to just add the data you need into the input itself using a custom data- attribute (ref). For example:

  <input type="checkbox" name="vehicle" value="Bike" data-extra="some extra data stored here instead of in a hidden table cell" data-price="250" />
   I am new
  row 1, cell 1 (this cell is hidden)
  row 1, cell 2 (this cell is hidden)

  <input type="checkbox" name="vehicle" value="Bike" data-extra="some extra data" data-price="300"/>
   I am new
  row 2, cell 1 (this cell is hidden)
  row 2, cell 2 (this cell is hidden)

Then you could just use this script (since you said only one checkbox is checked at a time):
var cell = $('#tbl :checked').attr('data-extra');


text:
Q: Onnxruntime Test Error after Successfully Converting Midas Model to ONNX Finally, I ask my first question. I've been struggling the past few days with this and couldn't find the same question here.
I converted this pretrained model to ONNX with this following codes:
import torch
from midas import midas_net
import onnx

model_path = "model-f46da743.pt"
model = midas_net.MidasNet(model_path, non_negative=True)
sample = torch.randn(1,3,384,672) # input_shape
torch.onnx.export(model,
                  sample,
                  "midas.onnx",
                  opset_version=11)

onnx_model = onnx.load("midas.onnx")
# Print a human readable representation of the graph
graph_output = onnx.helper.printable_graph(onnx_model.graph)
with open("graph.txt", mode="w") as fout:
    fout.write(graph_output)

I opened the midas.onnx with Netron and it looked good. And then I tried to test it with onnxruntime:
import torch
import utils
import cv2
from torchvision.transforms import Compose
from midas import transforms
import onnxruntime # Tool for scoring ONNX models
import onnx

# select device
device = torch.device("cpu")
# print("device: %s" % device)

model = "/home/ipu/libraries/MiDaS/midas.onnx"
sess = onnxruntime.InferenceSession(model) # Load a ONNX model
# print(sess) # <onnxruntime.capi.session.InferenceSession object at 0x7f07d5e10f10>

input_name = sess.get_inputs()[0].name
# print(input_name) # input.1

input_shape = sess.get_inputs()[0].shape
# print("input shape", input_shape) # [1, 3, 384, 672]

output_name = sess.get_outputs()[0].name
# print(output_name) # 1176

output_shape = sess.get_outputs()[0].shape
# print("output shape", output_shape) # [1, 384, 672]

# Check that the Intermediate Representation (IR) is well formed
# print("check onnx model ", onnx.checker.check_model(onnx.load(model))) # None

transform = Compose(
    [
        transforms.Resize(
            384,
            384,
            resize_target=None,
            keep_aspect_ratio=True,
            ensure_multiple_of=32,
            resize_method="lower_bound",
            image_interpolation_method=cv2.INTER_CUBIC,
        ),
        transforms.NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
        transforms.PrepareForNet(),
    ]
)

# get input
img = utils.read_image("input/20200629_123103.jpg")
img_input = transform({"image": img})["image"]

sample = torch.from_numpy(img_input).to(device).unsqueeze(0)
# print("sample", sample)
# print("sample shape", sample.shape) # torch.Size([1, 3, 384, 672])
# print(type(sample)) # <class 'torch.Tensor'>

def to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()

# print("to numpy sample", to_numpy(sample))
# print("to numpy sample shape", to_numpy(sample).shape) # (1, 3, 384, 672)
# print(type(to_numpy(sample))) # <class 'numpy.ndarray'>

# Input must be a list of dictionaries or a single numpy array
ort_outs = sess.run([output_name], {input_name: to_numpy(sample)})
print(ort_outs)

But, I got this error:
2020-07-15 10:55:23.402764485 [E:onnxruntime:, sequential_executor.cc:281 Execute] Non-zero status code returned while running Resize node. Name:'' Status Message: /onnxruntime_src/onnxruntime/core/providers/cpu/tensor/upsample.h:283 void onnxruntime::UpsampleBase::ScalesValidation(const std::vector<float>&, onnxruntime::UpsampleMode) const scales.size() == 2 || (scales.size() == 4 && scales[0] == 1 && scales[1] == 1) was false. 'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the Resize operator

Traceback (most recent call last):
  File "simple_test.py", line 73, in <module>
    ort_outs = sess.run([output_name], {input_name: to_numpy(sample)})
  File "/home/ipu/anaconda3/envs/midas/lib/python3.7/site-packages/onnxruntime/capi/session.py", line 111, in run
    return self._sess.run(output_names, input_feed, run_options)
onnxruntime.capi.onnxruntime_pybind11_state.RuntimeException: [ONNXRuntimeError] : 6 : RUNTIME_EXCEPTION : Non-zero status code returned while running Resize node. Name:'' Status Message: /onnxruntime_src/onnxruntime/core/providers/cpu/tensor/upsample.h:283 void onnxruntime::UpsampleBase::ScalesValidation(const std::vector<float>&, onnxruntime::UpsampleMode) const scales.size() == 2 || (scales.size() == 4 && scales[0] == 1 && scales[1] == 1) was false. 'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the Resize operator

For more info, I use Pytorch (1.3.1), ONNX (1.7.0) and Onnxruntime (1.3.0)
I would really appreciate any help.

A: Can you attach the onnx model? I can't seem to run the export script. It fails with this error "ImportError: cannot import name 'midas_net'".
Also, the error is pretty self-explanatory. Here scales is the scales array as mentioned here: https://github.com/onnx/onnx/blob/master/docs/Changelog.md#Resize-11. Does the scales input match the constraints mentioned in the error message?

A: I solved this with upgrading the pytorch version from 1.3.1 to 1.4.0.
conda install pytorch=1.4.0 -c pytorch


text:
Q: Best way to calculate the index of a character in a string given a pixel offset Related question: Getting a string index based on a pixel offset
I know this is close to that question, but this isn't asking how to do it directly, it's asking how to fake it best.

I am implementing my own text box for Windows Forms (because RichTextBox sucks) and I am trying to find the best way to, given strings that have been drawn on the screen, calculate what character the mouse is over. The problem is that characters can be variable-width.
I have come up with two possibilities:

*

*Do Graphics.MeasureCharacterRange every time the mouse moves in a binary search fashion on the line that the mouse is over (as suggested in the question linked at the top)

*Keep a list of the offset of every character of every line.
(1) Will have bad performance, and
(2) will be memory-inefficient plus make typing a character become a O(n) operation (because you have to adjust the offset of every character after it) plus impossible to do precisely because Graphics.MeasureCharacterRange isn't precise (it returns one value for one character, another value for another character, and a totally different value [that does not equal the two previous values added together] for both of them together in one string. E.g. W will be 16 pixels wide and f will be 5 pixels wide, but Wf is 20 pixels wide. Those numbers are from an actual test.).
So I am looking for a better strategy to do this, preferably one that requires minimal space and O(1) computational complexity (though I will gladly trade off a little memory efficiency for speed efficiency).

A: I don't think you have to do O(1).   O(1) is assuming that every additional character has an affect on ALL previous characters, which it would not.  At best I would see an O(1) for each word which should be crazy fast.  It sounds like what you need is a way to store; 1 the location of each word, 2 each unique word, and 3 the width of each letter in the word.  This would significantly reduce the storage and increase look up speed.  Maybe something like:
IEnumerable<TextLocation> TextLocations = ...;

internal class TextLocation
{
    public RectF BoundingBox { get; set; }  //this is relative to the textbox
    public TextWord TextWord { get; set; }
}

internal class TextWord
{
    public string Text { get; set; }
    public IEnumerable<LetterInfo> Letters { get; set; }
}

internal class LetterInfo
{
    public char Letter { get; set; }
    public float left { get; set; }  //these would be relative to the bounding box
    public float right { get; set; } //not to the textbox
}

Then you might be able to do something like
var tl = TextLocations.FirstOrDefault(x => x.BoundingBox.Left < Mouse.X
                                           && x.BoundingBox.Right > Mouse.X
                                           && x.BoundingBox.Top < Mouse.Y
                                           && x.BoundingBox.Bottom > Mouse.Y)

if (tl != null)
{
    //tl.TextWord.Text is the Word ("The", "Lazy", "Dog"...)

    var letter = tl.TextWord.Letters
                   .FirstOrDefault(x => Mouse.x - tl.BoundingBox.left > x.left
                                        Mouse.x - tl.BoundingBox.left < x.right);

    if (letter != null)
    {
        // you get the idea
    }
}


text:
Q: Server Sent Events Delay Problem: Some events take 1/2 minutes to reach client.
Setup: I have a nodejs backend trying to send events using SSE to a React App client, while having nginx as a proxy. Deployed in aws with fargate task and load balancer.
The events eventually reach the client, but take alot of time making it useless for my use case.
Backend Code:
Endpoint to start connection:
handler: async (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  })

  const id = Date.now()
  const data = { id, response: res }
  emitterList.push(data) // array with the responses

  setTimeout(() => {
    res.end()
    remove(id)
  }, 2 * 60 * 1000)

  req.on('close', () => { remove(id) })
}

Endpoint to push data to connected clients
emitterList
  .forEach(elem => {
    try {
      console.log('WRITE: ', new Date())
      elem.response.write(`data: ${JSON.stringify(data)}`)
      elem.response.write(`\n\n`)
    } catch(err) {
      deadEmitters.push(elem.id)
    }
    removeDeadEmitters()

Client Code:
 const eventSource = new EventSource(`${process.env.REACT_APP_BACKEND_BASE_URL}/emitter/${id}`)
eventSource.onmessage = (e) => { console.log(new Date()) }

Is there any configuration i need to set in nginx?

A: The solution was to add the header 'X-Accel-Buffering': 'no' in the response.