text:
Q: Couple of crash logs got me stumped During testing 2 of my beta testers have reported crashes. These are the only 2 and both experience a different crash. I just can not see what is causing the crashes. I hoped if I post one here someone can nudge me in the right direction.
Incident Identifier: FE4706B0-96FB-4F6A-89A3-14965A89D4C9
Beta Identifier:     5AB9E26F-1DF9-4826-B9F4-D51E7529306E
Hardware Model:      iPhone7,2
Process:             AnApplication [356]
Path:                /private/var/mobile/Containers/Bundle/Application/C1F6D736-BB16-4604-965A-5AFED492B02C/We Motovlog.app/We Motovlog
Identifier:          com.aWebAddresss.We-Motovlog
Version:             1.0.8 (1.0)
Beta:                YES
Code Type:           ARM-64 (Native)
Parent Process:      launchd [1]

Date/Time:           2015-10-01 21:13:21.21 +0100
Launch Time:         2015-10-01 21:12:53.53 +0100
OS Version:          iOS 9.0.1 (13A404)
Report Version:      105

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001000b5224
Triggered by Thread:  0

Global Trace Buffer (reverse chronological seconds):
12.054284    CFNetwork                  0x000000018247d9a4 TCP Conn 0x15fdb5800 SSL Handshake DONE
12.240634    CFNetwork                  0x000000018247d8b4 TCP Conn 0x15fdb5800 starting SSL negotiation
12.241194    CFNetwork                  0x000000018251f760 TCP Conn 0x15fdb5800 complete. fd: 6, err: 0
12.242804    CFNetwork                  0x0000000182520c8c TCP Conn 0x15fdb5800 event 1. err: 0
12.329534    CFNetwork                  0x0000000182520d64 TCP Conn 0x15fdb5800 started
12.333102    CFNetwork                  0x00000001825765a4 Creating default cookie storage with default identifier
12.333102    CFNetwork                  0x0000000182576570 Faulting in CFHTTPCookieStorage singleton
12.333103    CFNetwork                  0x00000001825c8498 Faulting in NSHTTPCookieStorage singleton
14.578179    CFNetwork                  0x000000018247d9a4 TCP Conn 0x15fe98dd0 SSL Handshake DONE
14.769610    CFNetwork                  0x000000018247d8b4 TCP Conn 0x15fe98dd0 starting SSL negotiation
14.770747    CFNetwork                  0x000000018251f760 TCP Conn 0x15fe98dd0 complete. fd: 6, err: 0
14.772033    CFNetwork                  0x0000000182520c8c TCP Conn 0x15fe98dd0 event 1. err: 0
14.854070    CFNetwork                  0x0000000182520d64 TCP Conn 0x15fe98dd0 started
15.166164    CFNetwork                  0x000000018247d9a4 TCP Conn 0x15fd7e620 SSL Handshake DONE
15.549554    CFNetwork                  0x000000018247d8b4 TCP Conn 0x15fd7e620 starting SSL negotiation
15.550051    CFNetwork                  0x000000018251f760 TCP Conn 0x15fd7e620 complete. fd: 6, err: 0
15.551401    CFNetwork                  0x0000000182520c8c TCP Conn 0x15fd7e620 event 1. err: 0
15.640146    CFNetwork                  0x0000000182520d64 TCP Conn 0x15fd7e620 started
27.110642    CFNetwork                  0x000000018247d9a4 TCP Conn 0x15fda0c10 SSL Handshake DONE
27.397462    CFNetwork                  0x000000018247d8b4 TCP Conn 0x15fda0c10 starting SSL negotiation
27.397862    CFNetwork                  0x000000018251f760 TCP Conn 0x15fda0c10 complete. fd: 6, err: 0
27.398833    CFNetwork                  0x0000000182520c8c TCP Conn 0x15fda0c10 event 1. err: 0
27.651662    CFNetwork                  0x0000000182520d64 TCP Conn 0x15fda0c10 started

Thread 0 name:
Thread 0 Crashed:
0   We Motovlog                     0x00000001000b5224 RegisterViewController.insertUserConfirmedIntoDatabase() -> () (RegisterViewController.swift:0)
1   We Motovlog                     0x00000001000be268 RegisterViewController.(selectTwitterAccount(RegisterViewController) -> (NSNotification) -> ()).(closure #1).(closure #2) (RegisterViewController.swift:312)
2   UIKit                           0x000000018871f19c -[UIAlertController _fireOffActionOnTargetIfValidForAction:] + 100 (UIAlertController.m:1008)
3   UIKit                           0x000000018871f934 __85-[UIAlertController _dismissAnimated:triggeringAction:triggeredByPopoverDimmingView:]_block_invoke + 32 (UIAlertController.m:1142)
4   UIKit                           0x0000000188617c10 -[UIPresentationController transitionDidFinish:] + 1320 (UIPresentationController.m:294)
5   UIKit                           0x000000018861adf8 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke_2 + 188 (UIPresentationController.m:738)
6   UIKit                           0x00000001883fb0a4 -[_UIViewControllerTransitionContext completeTransition:] + 116 (UIViewControllerTransitioning.m:236)
7   UIKit                           0x0000000188309828 -[UIViewAnimationBlockDelegate _didEndBlockAnimation:finished:context:] + 628 (UIView.m:9265)
8   UIKit                           0x0000000188309324 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 312 (UIView.m:1271)
9   UIKit                           0x00000001883091ac -[UIViewAnimationState animationDidStop:finished:] + 108 (UIView.m:1310)
10  QuartzCore                      0x0000000187ad9040 CA::Layer::run_animation_callbacks(void*) + 284 (CALayer.mm:6653)
11  libdispatch.dylib               0x0000000198165770 _dispatch_client_callout + 16 (object.m:513)
12  libdispatch.dylib               0x000000019816ae20 _dispatch_main_queue_callback_4CF + 1844 (inline_internal.h:1063)
13  CoreFoundation                  0x0000000182d30258 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12 (CFRunLoop.c:1615)
14  CoreFoundation                  0x0000000182d2e0c0 __CFRunLoopRun + 1628 (CFRunLoop.c:2721)
15  CoreFoundation                  0x0000000182c5cdc0 CFRunLoopRunSpecific + 384 (CFRunLoop.c:2814)
16  GraphicsServices                0x000000018ddb0088 GSEventRunModal + 180 (GSEvent.c:2247)
17  UIKit                           0x0000000188336f60 UIApplicationMain + 204 (UIApplication.m:3663)
18  We Motovlog                     0x00000001000c14c0 main (AppDelegate.swift:19)
19  libdyld.dylib                   0x00000001981968b8 start + 4 (start_glue.s:80)

And the code that it appears to be crashing on.
func insertUserConfirmedIntoDatabase(){

    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.synchronize()

    var parameters = ""

    if let YouTubeChannelID = defaults.valueForKey("YTchannelID"){
        parameters = "YouTubeChannelID=\(YouTubeChannelID)&"
    }

    if let  TwitterID = defaults.valueForKey("chosenTwitterID"){
        parameters = parameters.stringByAppendingString("TwitterID=\(TwitterID)&")
    }

    if      let Subscribers = defaults.valueForKey("YTchannelsubscriberCount"){
        parameters = parameters.stringByAppendingString("Subscribers=\(Subscribers)&")
    }

    if  let VloggerYouTubeName = defaults.valueForKey("YTchannelName"){
        parameters = parameters.stringByAppendingString("VloggerYouTubeName=\(VloggerYouTubeName)&")        }

    if let VloggersEmail = defaults.valueForKey("usersEmail"){
        parameters = parameters.stringByAppendingString("VloggersEmail=\(VloggersEmail)&")
    }

    if let  VloggersUserID = defaults.valueForKey("userGoogleID"){
        parameters = parameters.stringByAppendingString("VloggersUserID=\(VloggersUserID)&")
    }

    if  let VloggersCountry = defaults.valueForKey("YTchannelCountry"){
        parameters = parameters.stringByAppendingString("VloggersCountry=\(VloggersCountry)&")
    }

    if  let VloggerYouTubeTitle = defaults.valueForKey("YTchannelTitle"){
        parameters = parameters.stringByAppendingString("VloggerYouTubeTitle=\(VloggerYouTubeTitle)")
    }

    let url = NSURL(string: "https://website.com/TMVUKApp/updateProfile.php?\(parameters)")!
    print("if let params \(url)")

    let request = NSURLRequest(URL: url)

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request) {

        (data, response, error) -> Void in

        if error == nil{

            self.performSegueWithIdentifier("loggedInSegue", sender: nil)
        }
    }

    task.resume()

}

and the code that calls

insertUserConfirmedIntoDatabase()

func selectTwitterAccount(notification: NSNotification){

        let selectTwitterAccount = UIAlertController(title: "Select the account associated with your youTube persona", message: "", preferredStyle: .Alert)
        let receivedDictionary = notification.userInfo!
        let arrayOfUsernames = receivedDictionary["usernames"] as! NSArray
        NSNotificationCenter.defaultCenter().removeObserver(self, name: "selectTwitterAccountNotification", object: nil)
        for username in arrayOfUsernames{
            selectTwitterAccount.addAction(UIAlertAction(title: username.username, style: UIAlertActionStyle.Default, handler: { (alertAction) -> Void in
                NSUserDefaults.standardUserDefaults().setValue(username.username!, forKey: "chosenTwitterID")
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "userhasConfirmedProfile")
                NSUserDefaults.standardUserDefaults().synchronize()

                self.insertUserConfirmedIntoDatabase()

            }))

        }
        selectTwitterAccount.addAction(UIAlertAction(title: "No twitter", style:UIAlertActionStyle.Destructive, handler: { (UIAlertAction) -> Void in
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "userhasConfirmedProfile")
            NSUserDefaults.standardUserDefaults().synchronize()
            self.insertUserConfirmedIntoDatabase()
        }))
    dispatch_async(dispatch_get_main_queue(), {
        self.presentViewController(selectTwitterAccount, animated: true) { () -> Void in

        }
    })
}

This is one of the crashes that is only happening to 1 user. I first thought it may be down to some of the NSUserDefaults not being set but I've handled those with if let statements but still it crashes.
As always any help will be gratefully received in helping me debug this problem.
Why does it crash?

A: My guess is something to do with the session.dataTaskWithRequest() call. Try getting your app into a state right before that code would be called, then shut off all your internet connections and perform whatever action you would to trigger that code to run. That will 'simulate' a lost connection in the middle of using the app.

A: I recently found some very similar issues, with users crashing and loosing their credentials. The log shows:
    1.087128     CFNetwork                  0x0000000183f22608 Creating default cookie storage with default identifier
    1.087128     CFNetwork                  0x0000000183f225d4 Faulting in CFHTTPCookieStorage singleton
    1.087128     CFNetwork                  0x0000000183f74394 Faulting in NSHTTPCookieStorage singleton

I was using setValue() for months and the crashes started a couple of weeks ago. Changing setValue into setObject seems to help. No issues the last couple of days. Waiting for AppStore release.


text:
Q: How to parse a zipped file completely from RAM? Background
I need to parse some zip files of various types (getting some inner files content for one purpose or another, including getting their names).
Some of the files are not reachable via file-path, as Android has Uri to reach them, and as sometimes the zip file is inside another zip file. With the push to use SAF, it's even less possible to use file-path in some cases.
For this, we have 2 main ways to handle: ZipFile class and ZipInputStream class.
The problem
When we have a file-path, ZipFile is a perfect solution. It's also very efficient in terms of speed.
However, for the rest of the cases, ZipInputStream could reach issues, such as this one, which has a problematic zip file, and cause this exception:
  java.util.zip.ZipException: only DEFLATED entries can have EXT descriptor
        at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:321)
        at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:124)

What I've tried
The only always-working solution would be to copy the file to somewhere else, where you could parse it using ZipFile, but this is inefficient and requires you to have free storage, as well as remove the file when you are done with it.
So, what I've found is that Apache has a nice, pure Java library (here) to parse Zip files, and for some reason its InputStream solution (called "ZipArchiveInputStream") seem even more efficient than the native ZipInputStream class.
As opposed to what we have in the native framework, the library offers a bit more flexibility. I could, for example, load the entire zip file into bytes array, and let the library handle it as usual, and this works even for the problematic Zip files I've mentioned:
org.apache.commons.compress.archivers.zip.ZipFile(SeekableInMemoryByteChannel(byteArray)).use { zipFile ->
    for (entry in zipFile.entries) {
      val name = entry.name
      ... // use the zipFile like you do with native framework

gradle dependency:
// http://commons.apache.org/proper/commons-compress/ https://mvnrepository.com/artifact/org.apache.commons/commons-compress
implementation 'org.apache.commons:commons-compress:1.20'

Sadly, this isn't always possible, because it depends on having the heap memory hold the entire zip file, and on Android it gets even more limited, because the heap size could be relatively small (heap could be 100MB while the file is 200MB). As opposed to a PC which can have a huge heap memory being set, for Android it's not flexible at all.
So, I searched for a solution that has JNI instead, to have the entire ZIP file loaded into byte array there, not going to the heap (at least not entirely). This could be a nicer workaround because if the ZIP could be fit in the device's RAM instead of the heap, it could prevent me from reaching OOM while also not needing to have an extra file.
I've found this library called "larray" which seems promising , but sadly when I tried using it, it crashed, because its requirements include having a full JVM, meaning not suitable for Android.
EDIT: seeing that I can't find any library and any built-in class, I tried to use JNI myself. Sadly I'm very rusty with it, and I looked at an old repository I've made a long time ago to perform some operations on Bitmaps (here). This is what I came up with :
native-lib.cpp
#include <jni.h>
#include <android/log.h>
#include <cstdio>
#include <android/bitmap.h>
#include <cstring>
#include <unistd.h>

class JniBytesArray {
public:
    uint32_t *_storedData;

    JniBytesArray() {
        _storedData = NULL;
    }
};

extern "C" {
JNIEXPORT jobject JNICALL Java_com_lb_myapplication_JniByteArrayHolder_allocate(
        JNIEnv *env, jobject obj, jlong size) {
    auto *jniBytesArray = new JniBytesArray();
    auto *array = new uint32_t[size];
    for (int i = 0; i < size; ++i)
        array[i] = 0;
    jniBytesArray->_storedData = array;
    return env->NewDirectByteBuffer(jniBytesArray, 0);
}
}

JniByteArrayHolder.kt
class JniByteArrayHolder {
    external fun allocate(size: Long): ByteBuffer

    companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }
}

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        thread {
            printMemStats()
            val jniByteArrayHolder = JniByteArrayHolder()
            val byteBuffer = jniByteArrayHolder.allocate(1L * 1024L)
            printMemStats()
        }
    }

    fun printMemStats() {
        val memoryInfo = ActivityManager.MemoryInfo()
        (getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
        val nativeHeapSize = memoryInfo.totalMem
        val nativeHeapFreeSize = memoryInfo.availMem
        val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
        val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
        Log.d("AppLog", "total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
                "free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
                "used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)")
    }

This doesn't seem right, because if I try to create a 1GB byte array using jniByteArrayHolder.allocate(1L * 1024L * 1024L * 1024L) , it crashes without any exception or error logs.
The questions

*

*Is it possible to use JNI for Apache's library, so that it will handle the ZIP file content which is contained within JNI's "world" ?

*If so, how can I do it? Is there any sample of how to do it? Is there a class for it? Or do I have to implement it myself? If so, can you please show how it's done in JNI?

*If it's not possible, what other way is there to do it? Maybe alternative to what Apache has?

*For the solution of JNI, how come it doesn't work well ? How could I efficiently copy the bytes from the stream into the JNI byte array (my guess is that it will be via a buffer)?

A: I took a look at the JNI code you posted and made a couple of changes. Mostly it is defining the size argument for NewDirectByteBuffer and using malloc().
Here is the output of the log after allocating 800mb:

D/AppLog: total:1.57 GB free:1.03 GB used:541 MB (34%)
  D/AppLog: total:1.57 GB free:247 MB used:1.32 GB (84%)

And the following is what the buffer looks like after the allocation. As you can see, the debugger is reporting a limit of 800mb which is what we expect.

My C is very rusty, so I am sure that there is some work to be done. I have updated the code to be a little more robust and to allow for the freeing of memory.
native-lib.cpp
extern "C" {
static jbyteArray *_holdBuffer = NULL;
static jobject _directBuffer = NULL;
/*
    This routine is not re-entrant and can handle only one buffer at a time. If a buffer is
    allocated then it must be released before the next one is allocated.
 */
JNIEXPORT
jobject JNICALL Java_com_example_zipfileinmemoryjni_JniByteArrayHolder_allocate(
        JNIEnv *env, jobject obj, jlong size) {
    if (_holdBuffer != NULL || _directBuffer != NULL) {
        __android_log_print(ANDROID_LOG_ERROR, "JNI Routine",
                            "Call to JNI allocate() before freeBuffer()");
        return NULL;
    }

    // Max size for a direct buffer is the max of a jint even though NewDirectByteBuffer takes a
    // long. Clamp max size as follows:
    if (size > SIZE_T_MAX || size > INT_MAX || size <= 0) {
        jlong maxSize = SIZE_T_MAX < INT_MAX ? SIZE_T_MAX : INT_MAX;
        __android_log_print(ANDROID_LOG_ERROR, "JNI Routine",
                            "Native memory allocation request must be >0 and <= %lld but was %lld.\n",
                            maxSize, size);
        return NULL;
    }

    jbyteArray *array = (jbyteArray *) malloc(static_cast<size_t>(size));
    if (array == NULL) {
        __android_log_print(ANDROID_LOG_ERROR, "JNI Routine",
                            "Failed to allocate %lld bytes of native memory.\n",
                            size);
        return NULL;
    }

    jobject directBuffer = env->NewDirectByteBuffer(array, size);
    if (directBuffer == NULL) {
        free(array);
        __android_log_print(ANDROID_LOG_ERROR, "JNI Routine",
                            "Failed to create direct buffer of size %lld.\n",
                            size);
        return NULL;
    }
    // memset() is not really needed but we call it here to force Android to count
    // the consumed memory in the stats since it only seems to "count" dirty pages. (?)
    memset(array, 0xFF, static_cast<size_t>(size));
    _holdBuffer = array;

    // Get a global reference to the direct buffer so Java isn't tempted to GC it.
    _directBuffer = env->NewGlobalRef(directBuffer);
    return directBuffer;
}

JNIEXPORT void JNICALL Java_com_example_zipfileinmemoryjni_JniByteArrayHolder_freeBuffer(
        JNIEnv *env, jobject obj, jobject directBuffer) {

    if (_directBuffer == NULL || _holdBuffer == NULL) {
        __android_log_print(ANDROID_LOG_ERROR, "JNI Routine",
                            "Attempt to free unallocated buffer.");
        return;
    }

    jbyteArray *bufferLoc = (jbyteArray *) env->GetDirectBufferAddress(directBuffer);
    if (bufferLoc == NULL) {
        __android_log_print(ANDROID_LOG_ERROR, "JNI Routine",
                            "Failed to retrieve direct buffer location associated with ByteBuffer.");
        return;
    }

    if (bufferLoc != _holdBuffer) {
        __android_log_print(ANDROID_LOG_ERROR, "JNI Routine",
                            "DirectBuffer does not match that allocated.");
        return;
    }

    // Free the malloc'ed buffer and the global reference. Java can not GC the direct buffer.
    free(bufferLoc);
    env->DeleteGlobalRef(_directBuffer);
    _holdBuffer = NULL;
    _directBuffer = NULL;
}
}

I also updated the array holder:
class JniByteArrayHolder {
    external fun allocate(size: Long): ByteBuffer
    external fun freeBuffer(byteBuffer: ByteBuffer)

    companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }
}

I can confirm that this code along with the ByteBufferChannel class provided by Botje here works for Android versions before API 24. The SeekableByteChannel interface was introduced in API 24 and is needed by the ZipFile utility.
The maximum buffer size that can be allocated is the size of a jint and is due to the limitation of JNI. Larger data can be accommodated (if available) but would require multiple buffers and a way to handle them.
Here is the main activity for the sample app. An earlier version always assumed the the InputStream read buffer was was always filled and errored out when trying to put it to the ByteBuffer. This was fixed.
MainActivity.kt
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun onClick(view: View) {
        button.isEnabled = false
        status.text = getString(R.string.running)

        thread {
            printMemStats("Before buffer allocation:")
            var bufferSize = 0L
            // testzipfile.zip is not part of the project but any zip can be uploaded through the
            // device file manager or adb to test.
            val fileToRead = "$filesDir/testzipfile.zip"
            val inStream =
                if (File(fileToRead).exists()) {
                    FileInputStream(fileToRead).apply {
                        bufferSize = getFileSize(this)
                        close()
                    }
                    FileInputStream(fileToRead)
                } else {
                    // If testzipfile.zip doesn't exist, we will just look at this one which
                    // is part of the APK.
                    resources.openRawResource(R.raw.appapk).apply {
                        bufferSize = getFileSize(this)
                        close()
                    }
                    resources.openRawResource(R.raw.appapk)
                }
            // Allocate the buffer in native memory (off-heap).
            val jniByteArrayHolder = JniByteArrayHolder()
            val byteBuffer =
                if (bufferSize != 0L) {
                    jniByteArrayHolder.allocate(bufferSize)?.apply {
                        printMemStats("After buffer allocation")
                    }
                } else {
                    null
                }

            if (byteBuffer == null) {
                Log.d("Applog", "Failed to allocate $bufferSize bytes of native memory.")
            } else {
                Log.d("Applog", "Allocated ${Formatter.formatFileSize(this, bufferSize)} buffer.")
                val inBytes = ByteArray(4096)
                Log.d("Applog", "Starting buffered read...")
                while (inStream.available() > 0) {
                    byteBuffer.put(inBytes, 0, inStream.read(inBytes))
                }
                inStream.close()
                byteBuffer.flip()
                ZipFile(ByteBufferChannel(byteBuffer)).use {
                    Log.d("Applog", "Starting Zip file name dump...")
                    for (entry in it.entries) {
                        Log.d("Applog", "Zip name: ${entry.name}")
                        val zis = it.getInputStream(entry)
                        while (zis.available() > 0) {
                            zis.read(inBytes)
                        }
                    }
                }
                printMemStats("Before buffer release:")
                jniByteArrayHolder.freeBuffer(byteBuffer)
                printMemStats("After buffer release:")
            }
            runOnUiThread {
                status.text = getString(R.string.idle)
                button.isEnabled = true
                Log.d("Applog", "Done!")
            }
        }
    }

    /*
        This function is a little misleading since it does not reflect the true status of memory.
        After native buffer allocation, it waits until the memory is used before counting is as
        used. After release, it doesn't seem to count the memory as released until garbage
        collection. (My observations only.) Also, see the comment for memset() in native-lib.cpp
        which is a member of this project.
    */
    private fun printMemStats(desc: String? = null) {
        val memoryInfo = ActivityManager.MemoryInfo()
        (getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memoryInfo)
        val nativeHeapSize = memoryInfo.totalMem
        val nativeHeapFreeSize = memoryInfo.availMem
        val usedMemInBytes = nativeHeapSize - nativeHeapFreeSize
        val usedMemInPercentage = usedMemInBytes * 100 / nativeHeapSize
        val sDesc = desc?.run { "$this:\n" }
        Log.d(
            "AppLog", "$sDesc total:${Formatter.formatFileSize(this, nativeHeapSize)} " +
                    "free:${Formatter.formatFileSize(this, nativeHeapFreeSize)} " +
                    "used:${Formatter.formatFileSize(this, usedMemInBytes)} ($usedMemInPercentage%)"
        )
    }

    // Not a great way to do this but not the object of the demo.
    private fun getFileSize(inStream: InputStream): Long {
        var bufferSize = 0L
        while (inStream.available() > 0) {
            val toSkip = inStream.available().toLong()
            inStream.skip(toSkip)
            bufferSize += toSkip
        }
        return bufferSize
    }
}

A sample GitHub repository is here.

A: You can steal LWJGL's native memory management functions. It is BSD3 licensed, so you only have to mention somewhere that you are using code from it.
Step 1: given an InputStream is and a file size ZIP_SIZE, slurp the stream into a direct byte buffer created by LWJGL's org.lwjgl.system.MemoryUtil helper class:
ByteBuffer bb = MemoryUtil.memAlloc(ZIP_SIZE);
byte[] buf = new byte[4096]; // Play with the buffer size to see what works best
int read = 0;
while ((read = is.read(buf)) != -1) {
  bb.put(buf, 0, read);
}

Step 2: wrap the ByteBuffer in a ByteChannel.
Taken from this gist. You possibly want to strip the writing parts out.
package io.github.ncruces.utils;

import java.nio.ByteBuffer;
import java.nio.channels.NonWritableChannelException;
import java.nio.channels.SeekableByteChannel;

import static java.lang.Math.min;

public final class ByteBufferChannel implements SeekableByteChannel {
    private final ByteBuffer buf;

    public ByteBufferChannel(ByteBuffer buffer) {
        if (buffer == null) throw new NullPointerException();
        buf = buffer;
    }

    @Override
    public synchronized int read(ByteBuffer dst) {
        if (buf.remaining() == 0) return -1;

        int count = min(dst.remaining(), buf.remaining());
        if (count > 0) {
            ByteBuffer tmp = buf.slice();
            tmp.limit(count);
            dst.put(tmp);
            buf.position(buf.position() + count);
        }
        return count;
    }

    @Override
    public synchronized int write(ByteBuffer src) {
        if (buf.isReadOnly()) throw new NonWritableChannelException();

        int count = min(src.remaining(), buf.remaining());
        if (count > 0) {
            ByteBuffer tmp = src.slice();
            tmp.limit(count);
            buf.put(tmp);
            src.position(src.position() + count);
        }
        return count;
    }

    @Override
    public synchronized long position() {
        return buf.position();
    }

    @Override
    public synchronized ByteBufferChannel position(long newPosition) {
        if ((newPosition | Integer.MAX_VALUE - newPosition) < 0) throw new IllegalArgumentException();
        buf.position((int)newPosition);
        return this;
    }

    @Override
    public synchronized long size() { return buf.limit(); }

    @Override
    public synchronized ByteBufferChannel truncate(long size) {
        if ((size | Integer.MAX_VALUE - size) < 0) throw new IllegalArgumentException();
        int limit = buf.limit();
        if (limit > size) buf.limit((int)size);
        return this;
    }

    @Override
    public boolean isOpen() { return true; }

    @Override
    public void close() {}
}

Step 3: Use ZipFile as before:
ZipFile zf = new ZipFile(ByteBufferChannel(bb);
for (ZipEntry ze : zf) {
    ...
}

Step 4: Manually release the native buffer (preferably in a finally block):
MemoryUtil.memFree(bb);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sub-Hopf algebras of group algebras  Let $k$ be a field and $G$ a finite group. Is every sub-Hopf algebra over $k$ of the group algebra $k[G]$ of the form $k[U]$ for a subgroup $U$ of $G$ ?

A: Yes:  The dual $H^*$ is a quotient algebra of $k[G]$, and the latter is the commutative function algebra $\{f:G \to k\}$.  Thus $H = k[U]$ for a set $U$, and closure under multiplication then makes $U$ a group.
The nice thing about finite-dimensional Hopf algebras over a field:  You can turn them upside down.  Vector space duality is an involution on finite-dimensional Hopf algebras.  (But I think that this particular argument still works in the infinite-dimensional case:  $k[G]^*$ has a weak-* topology and $H^*$ is a quotient by a closed ideal, so it should still create $U$.)

A: Moreover, finiteness of $G$ is irrelevant as Greg's proof works there as well. BTW, you don't need to go into $H^\ast$ if you are willing to use coalgebras: any subcoalgebra of $k[G]$ is $k[U]$ for some subset of $G$. $U$ must be a subgroup for the subco to be subHopf...
A more interesting question is to ask about forms of $k[G]$, i.e. Hopf algebras over a subfield $m$ such that $k\otimes_m H \cong k[G]$. There are a plenty of those which are not group subalgebras!!


text:
Q: Including 3rd Party Modules in Angular App I would like to include a couple of 3rd party Angular modules in my App.  Previously I have only created simple apps that I simply use ng-app to bootstrap and put my code inside the controller.
From my understanding I should have something like this in my html:
<html ng-app"myApp">

Then my JS should look something like this:
angular.module('myApp',['thirdPartyModule1','thirdPartyModule2']);

var myCtrl = function($scope, myApp, $http){

    //my stuff
};

But when I do this I get an error:
Error: Unknown provider: myAppProvider <- myApp

A: You don't need to inject myApp into the controller. Your controller should be defined like this:
angular.module('myApp',['thirdPartyModule1','thirdPartyModule2']);

var myCtrl = function($scope, $http){
 //my stuff
});

to make it a little more "standard":
var myApp = angular.module('myApp',['thirdPartyModule1','thirdPartyModule2']);

myApp.controller('myCtrl', function($scope, $http){
  //my stuff
});

This way you can have a reference to your app if you like.
Now to make it compatible with minifiers/beautifiers/closure compiler:
var myApp = angular.module('myApp',['thirdPartyModule1','thirdPartyModule2']);

myApp.controller('myCtrl', ['$scope','$http', function($scope, $http){
  //my stuff
}]);

That basically makes the controller argument an array, where the first members of the array are what you're going to inject. This is because a minifier will turn the arguments into random letters like function(a,b) and angular won't know what the heck you want to inject. By passing strings in the array thy will be minified like so ['$scope','$http', function(a,b)] which is fine because the first two arguments in the array tell angular what to inject.


text:
Q: Can the minimum be given by an integral? for $a,b > 0$, $$ \begin{align} &\int_{0}^{\infty} \frac{\sin (ax) \sin (bx)}{x^{2}} \ dx  \\ &= \int_{0}^{\infty} \frac{a \cos (ax) \sin (bx) + b \sin(ax) \cos(bx)}{x} \ dx \\ &= \frac{a}{2} \int_{0}^{\infty} \frac{\sin[(a+b)x] - \sin [(a-b)x]}{x} \ dx + \frac{b}{2} \int_{0}^{\infty} \frac{\sin [(a+b)x] + \sin[(a-b)x]}{x} \ dx \\ &= \frac{a}{2} \left( \frac{\pi}{2} - \frac{\pi}{2} \text{sgn} (a-b) \right) + \frac{b}{2} \left(\frac{\pi}{2} + \frac{\pi}{2} \text{sgn} (a-b) \right) \\ &= \frac{\pi}{2} \min \{a,b \} . \end{align}$$
So we can express the minimum of 2 positive real values by an integral.
We can for example also express the Lambert-W function by an integral where the integrand contains only elementary functions.
So we are also capable of expressing the functional inverse by an integral.
We can also express the $n$ th derivative of a function by an integral.
This inspired me to wonder about a combination of the above.
for $x>0$ and $f$ a real-analytic function :
$min(f(x))$.
Can this be given by an integral ?
Notice $min(f(x)) = f(y)$ where $y$ is one of the solutions to $f ' (y) = 0$ so the derivative and functional inverse are naturally related to the minimum.
I have never seen such an integral for a general $f(x)$ so I wonder if it exists.


text:
Q: Conditional Statements difference Is there any difference between below two statements
if (null != obj)

and
if (obj != null)

If both treated same which will be preferable?

A: The difference here is the code generated. The two will not generate the exact same code, but in practice this will have no bearing on the results or performance of the two statements.
However, if you create your own types, and override the inequality operator, and do a poor job, then it will matter.
Consider this:
public class TestClass
{
    ...

    public static bool operator !=(TestClass left, TestClass right)
    {
        return !left.Equals(right);
    }
}

In this case, if the first argument to the operator is null, ie. if (null != obj), then it will crash with a NullReferenceException.
So to summarize:

*

*The code generated is different

*The performance and end results should be the same

*

*Except when you have broken code in the type involved

Now, the reason I think you're asking is that you've seen code from C, which typically had code like this:
if (null == obj)

Note that I switched to equality check here. The reason is that a frequent bug in programs written with old C compilers (these days they tend to catch this problem) would be to switch it around and forget one of the equal characters, ie. this:
if (obj = null)

This assigns null to the variable instead of comparing it. The best way to combat this bug, back then, would be to switch it around, since you can't assign anything to null, it's not a variable. ie. this would fail to compile:
if (null = obj)

A: No, but the second way is more common and more readable (and more logical in my opinion)

A: The first is a Yoda condition. Use it you should not.

A: No, there is not. It's exactly the same.
The style null == obj is sometimes just used to prevent the common typo obj = null to not accidently assign null to a variable, but with != there's absolutely no reason to do so.
In .NET it won't actually compile for the typo obj = null.
So the compiler prevents you from   accidently doing it.
The Yoda condition comes originally from other languages, where this compiler feature is missing.

A: They are exactly the same.
Some people prefer to put the null as the first part of the expression to avoid errors like this
if (obj = null)  // should be obj == null

But of course this doesn't apply to the != operator, so in your example it's just a difference of style.

A: First type of statement came from C/C++, where was possible to pass not boolean values to condition verification. E.g. anything not 0 was true, and zero was false:
if (5) { } // true
if (0) { } // false

Sometimes it created problems if you forgot to type one '=' char:
if (x = 5) { }   // this was true always and changed x value
if (x == 5) { }  // this was true, if x was equal to 5

So, Yoda syntax was used, to receive compiler error in case one '=' was missed:
if (5 = x) { }   // this was generating compiler error for absent-minded programmers
if (5 == x) { }  // this was true, if x was equal to 5

C# allow only boolean value in conditions, So
if (x = 5) { }   // this won't compile
if (x == 5) { }  // this is true, if x was equal to 5

What about boolean types?
if (y = true) { }
if (y == true) { }

Well, this is useless code, because you can just write if (y).
Conclusion: Yoda syntax is gone with C/C++ and you do not need to use it anymore.

A: The use of the first form
if (blah == obj)

stems from the days when compilers would not catch  if (obj = blah)  i.e. unintentional assignment, unless compile warning level was set to maximum


text:
Q: Understanding the proof that a non-abelian group of order $pq$ ($pI recently tried to come up with my own proof of the following: Let $p$ and $q$ be primes with $p<q$. Prove that a non-abelian group $G$ of order $pq$ has a nonnormal subgroup of index $q$. I found the following proof from this link:
Prove that a non-abelian group of order $pq$ ($p<q$) has a nonnormal subgroup of index $q$

Let $K$ be a subgroup of order $q$ of $G$. $K$ exists by Cauchy's Theorem. Then index$[G:K]=p$, the smallest prime dividing $|G|$. Now let $G$ act on the left cosets of $K$ by left-multiplication. The kernel of this action $C=core_G(K)$ is normal in $G$ and $G/C$ injects homomorphically in $S_p$. So $|G/C| \mid p!$.  Since $p \lt q$, it follows that $|G/C|=p$, whence $K=C$, and $K$ is normal.Now $G$ has a subgroup $H$ of order $p$. If it is normal, then we would have $H \cap K =1$ and $|HK|=|H||K|/|H\cap K|=pq$, so $G=HK$, and $G \cong H \times K \cong C_{pq}$, and $G$ would be abelian. So $H$ must be non-normal.

I understand that Cauchy's Theorem implies the existence of $K$, a group of prime order. Since the index $[G:K]=p$ is the smallest prime dividing $|G|$, $K$ is normal in $G$ (Dummit and Foote,  page 120). But what's the purpose of the remaining paragraph when it's apparent that $core_G(K)=\bigcap_{g\in G} gKg^{-1}=K$ since $K$ is normal?
And I know that the 1st. isomorphism thm. implies that $|G/core_G(K)|\mid p!$. But I don't think the deduction 'Since $p \lt q$, it follows that $|G/core_G(K)|=p$' is valid: $|G/core_G(K)|=p$ is immediately followed by the fact that $core_G(K)=K$. However, the '$p<q$' seems to be crucial in the proof of the proposition. Just consider $Sym(3)$. It has order $6$, and has $3$ nonnormal subgroups of index $3$, but the only subgroup of index $2$ is normal. So how to appropriately employ the assumption '$p<q$' in the proof?
Another question regarding the second paragraph: 'Now $G$ has a subgroup $H$ of order $p$. If it is normal, then we would have $H \cap K =1$'. Why the 'If it is normal' if $H$ and $K$ have coprime orders implying that $H \cap K =1$?

A: First of all about your last question: $H$ and $K$ being normal has nothing to do with $H \cap K= \{\ e \}\ $. The order $H$ and $K$ being co-prime plays the role here. $H$ and $K$  being normal plays the part where you write $HK \cong H \times K$. If both are not normal you won't get a direct product then. Here $K$ which is surely normal of order q and $H$ if normal (of order p) gives you $G \cong C_{p} \times C_{q}$. But if $H$ is  not normal, you will get non-abelian group which are actually semi-direct products of $C_{p}$ and $C_{q}$.
Now about the other question about how to effectively use $p<q$ in the proof. See if you use the Sylow theorems then it's quiet evident. But if you don't want to use that there is another easy way to see this.
Use the fact that if there is a unique subgroup of order n in a group, then that subgroup has to be normal.(You should know why?).
Let $K_{1}$ and $K_{2}$ be two distinct subgroups of order q. Then $|K_{1}K_{2}|=q^{2}$(why?). But $q^{2} > pq$ since $p<q$. Hence a contradiction!!
So, You have a unique subgroup of order q and hence normal.

A: The purpose of the rest of the first paragraph is to prove the special case (perhaps) needed here of the statement from Dummit and Foote that you mention.
In fact, this argument proves it in general. We have
$$p[K:C] = [G:K][K:C] = [G:C] | p!, \quad \text{hence} \quad [K:C]|(p-1)!.$$
Since $|K|$ divides $|G|$, it cannot be divisible by any prime number smaller than $p$. This proves that $[K:C] = 1$, hence that $K = C$.
The "if it is normal" assumption isn't really needed to prove that $H \cap K = \{1\}$. It's only used to go from $G = HK$ to $G \cong H \times K$.


text:
Q: @ResponseBody not producing XML in Java 6 I have a Spring MVC 3/J2EE Project.  The jsp rendering controllers are working fine, but the one controller that renders XML for Ajax is not working.  I am using JDK 1.6 in RAD 7.5 so JAXB should be on the classpath, and I've even tried adding the latest JAXB jars to the lib file to make sure.  I still get a 406 error when I make the call.  My DOJO call has handleAs: "xml", and I've confirmed that application/xml is on the Accept header via FireBug.  I have the <mvc:annotation-driven /> line in my spring servlet xml file. I can see the method being invoked and returning without error.  I'm not sure what I should try next to debug.
//Country is a class with only primative types which implements Serializable.
public @ResponseBody List<Country> getCountries(){
    return addressService.getCountries();
}

function loadData(){
    console.log("Before get ...");
    dojo.xhrGet({
        url:"http://localhost:9080/sample/shared/getCountries.htm",
        handleAs:"xml",
        load: function(data){
            console.log("In load function ...");
            try {
                for(var i in data){
                   console.log("key", i, "value", data[i]);
                }
            }catch (ex){
                console.error("Failure in load function: " + ex);
            }
            console.log("Exiting load function ...");
        },
        error: function(x){
            console.error("Error in ajax ...");
            console.error(x);
        },
        failOk: false
    });
    console.log("After get ...");
}

A: Try creating the following wrapper class:
@XmlRootElement
class Countries {
    private List<Country> countries = new ArrayList<Country>()

    //getters/setters
}

And return it from the controller instead of a raw list:
public @ResponseBody Countries getCountries()

Most likely your problem is caused by JAXB that is unable to marshal Java list (it does not know how to name the root tag of the XML document). Note that your problem probably does not occur when requesting data in JSON (if Jackson is available on your CLASSPATH).
See also (similar problems):

*

*Spring MVC 3: Returning XML through @ResponseBody

*issues with xml in spring mvc 3

A: Hard to say without seeing how you have configured your views / view resolvers. However, the client-side URL containing a .htm is suspect to me, especially if you are using a ContentNegotiatingViewResolver. I recommend dropping the file extension. Browsers automatically use an Accept header for HTML so no need to use an extension.


text:
Q: Paragraph alignment problem when the line ended with a 2 words being separated by a "/" At the end of one of my sentence 2 words are separated by a "/". The line is not justified. Why? How to fix it?
\documentclass[preprint,12pt]{elsarticle}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage{amssymb}
\usepackage{lineno}
\usepackage[colorlinks=true]{hyperref}
\usepackage{natbib}
\usepackage{footnotebackref}
\usepackage{changepage}
\frenchspacing
\usepackage{times}

\makeatletter % <-Added code from here
\def\ps@pprintTitle{%
 \let\@oddhead\@empty
 \let\@evenhead\@empty
 \def\@oddfoot{}%
 \let\@evenfoot\@oddfoot}
\makeatother

\usepackage{csquotes}
\MakeOuterQuote{"}
\usepackage{etoolbox}
\patchcmd{\keyword}{\textit}{}{}{}
\usepackage{setspace}
\doublespacing

\begin{document}
With all of good/bad on the one side and versions of reductionism/non-reductionism on the other, I recently dealt with the same task, so here I present my solution: I defined a new columntype Y to center the cells in a tabularx environment. I recently dealt with the same task, so here I present my solution: I defined a new columntype Y to center the cells in a tabularx environment. I recently dealt with the same task, so here I present my solution: I defined a new columntype Y to center the cells in a tabularx environment. I recently dealt with the same task, so here I present my solution: I defined a new columntype Y to center the cells in a tabularx environment.
\end{document}

A: TeX is programmed, by default, never to hyphenate words which already contain hyphens. In the example you gave, the problem word is non-reductionism, as may be verified in the first paragraph of the screenshot shown below. The result is a massively overfull line.
One way to override is to insert the directive \hspace{0pt} immediately after the hyphen character, i.e., to write the word as non-\hspace{0pt}reductionism. Check out the middle paragraph for the resulting look.
At least for the paragraph you provided, the presence of a / ("slash") character between reductionism and non-reductionism is actually irrelevant, as may be verified by comparing the middle and bottom paragraphs below; the only difference is in the bottom paragraphs, both / characters were replaced by the macro \slash.

If don't like the look of a word that contains two hyphenation characters (one of them being at the end of a line), the only remedy that's left is to rewrite the paragraph suitably.
\documentclass[12pt]{elsarticle}
% (I've retained only the bare essentials...)
\usepackage[english]{babel}
\frenchspacing
\usepackage{times}
\hyphenation{non-re-duc-tion-ism}

\begin{document}
With all of good/bad on the one side and versions of
reductionism/non-reductionism on the other, I recently
dealt with the same task, so here I present my solution:
I defined a new columntype\dots

\medskip
With all of good/bad on the one side and versions of
reductionism/non-\hspace{0pt}reductionism on the other,
I recently dealt with the same task, so here I present
my solution: I defined a new columntype\dots

\medskip
With all of good\slash bad on the one side and versions of
reductionism\slash non-\hspace{0pt}reductionism on the other,
I recently dealt with the same task, so here I present
my solution: I defined a new columntype\dots
\end{document}


text:
Q: JRE 1.7u45 unable to load an applet containing some unsigned entries I am getting the following error while loading a java applet on JRE 1.7u45.
    java.lang.SecurityException: com.sun.deploy.net.JARSigningException:
    Found unsigned entry in resource #name of the applet#
    at com.sun.deploy.cache.CacheEntry.getJarFile(Unknown Source)
    at com.sun.deploy.model.ResourceProvider.getCachedJarFile(Unknown Source)
    at sun.plugin.PluginURLJarFileCallBack$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin.PluginURLJarFileCallBack.retrieve(Unknown Source)
    at sun.net.www.protocol.jar.URLJarFile.retrieve(Unknown Source)
    at sun.net.www.protocol.jar.URLJarFile.getJarFile(Unknown Source)
    at sun.net.www.protocol.jar.JarFileFactory.get(Unknown Source)
    at sun.net.www.protocol.jar.JarURLConnection.connect(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.connect(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFileInternal(Unknown Source)
    at sun.plugin.net.protocol.jar.CachedJarURLConnection.getJarFile(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.getJarFile(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.access$1000(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.ensureOpen(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$JarLoader.<init>(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source)
    at com.sun.deploy.security.DeployURLClassPath.getResource(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.plugin2.applet.Plugin2ClassLoader.findClassHelper(Unknown Source)
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

This applet indeed contains one unsigned entry. However I cannot get this entry signed immediately because of third party technical issues.
The same applet worked fine on JRE 1.7u40, but apparently there has been some change in JRE 1.7u45 adding some additional security features.
I tried to reduce the security level in Java to medium. This works on MAC but unfortunately does not work on windows.
Any suggestions/workaround to get the applet to work would be greatly appreciated!

A: To work around this, I just disabled Java cache on endpoint machine and the applet started working fine.

A: If you are using libraries that are already compiled and packaged into JARs, and signed by the author, you do not have to worry about signing them.  But say, you've used someone else's source code (open source hopefully) and have compiled it on your own machine, you must remove the existing signature and re-sign that package.  If you are using Java applets, they must be signed now, unless you enjoy a mountain of pain.
Now, this also applies to the packaged libraries within your packaged jar.  If they have already been signed, leave them alone. But if you must sign them, make sure you remove any existing certificates from the JAR file before you do so, the same way as your main applet.
Additional information that may help:
Your MANIFEST.mf file in all JARs must contain entries for the the properties, as shown in the example below:
Application-Library-Allowable-Codebase: *
Permissions: all-permissions
Caller-Allowable-Codebase: *
Codebase: *
Application-Name: POSInterface

TIP
If you're deploying a bunch of applets to a web application, I like to automate this whole process of modifying the manifest and code-signing with a batch file and text file containing the above properties that need to be in the manifest.mf file, named addToManifest.txt.  Here is an example of how it's done:
@ECHO off
ECHO Changing manifest files for all...
jar ufm Applet_RFID.jar addToManifest.txt
jar ufm FingerPrintReader.jar addToManifest.txt
jar ufm jzebra.jar addToManifest.txt
jar ufm POSInterface.jar addToManifest.txt
jar ufm lib\access-bridge-32.jar addToManifest.txt
jar ufm lib\addToManifest.txt addToManifest.txt
jar ufm lib\dnsns.jar addToManifest.txt
jar ufm lib\dpuareu.jar addToManifest.txt
jar ufm lib\epsonupos.admin.jar addToManifest.txt
jar ufm lib\epsonupos.core.v1.13.0001.jar addToManifest.txt
jar ufm lib\epsonupos.H2000.jar addToManifest.txt
jar ufm lib\epsonupos.H6000IV.jar addToManifest.txt
jar ufm lib\epsonupos.jar addToManifest.txt
jar ufm lib\epsonupos.T20.jar addToManifest.txt
jar ufm lib\epsonupos.T81.jar addToManifest.txt
jar ufm lib\epsonupos.T81II.jar addToManifest.txt
jar ufm lib\epsonupos.T82.jar addToManifest.txt
jar ufm lib\epsonupos.T88V.jar addToManifest.txt
jar ufm lib\epsonupos.trace.jar addToManifest.txt
jar ufm lib\HWHydraSO.jar addToManifest.txt
jar ufm lib\jaccess.jar addToManifest.txt
jar ufm lib\jcl_editor.jar addToManifest.txt
jar ufm lib\jpos113-controls.jar addToManifest.txt
jar ufm lib\jpos113.jar addToManifest.txt
jar ufm lib\jssc_qz.jar addToManifest.txt
jar ufm lib\localedata.jar addToManifest.txt
jar ufm lib\plugin.jar addToManifest.txt
jar ufm lib\pos.jar addToManifest.txt
jar ufm lib\pos.v3.0001.jar addToManifest.txt
jar ufm lib\stario.jar addToManifest.txt
jar ufm lib\starjavapos.jar addToManifest.txt
jar ufm lib\sunec.jar addToManifest.txt
jar ufm lib\sunjce_provider.jar addToManifest.txt
jar ufm lib\sunmscapi.jar addToManifest.txt
jar ufm lib\sunpkcs11.jar addToManifest.txt
jar ufm lib\Symbol.RFID.API3.jar addToManifest.txt
jar ufm lib\uposcommon.core.v1.13.0001.jar addToManifest.txt
jar ufm lib\uposcommon.jar addToManifest.txt
jar ufm lib\xercesImpl.jar addToManifest.txt
jar ufm lib\xml-apis.jar addToManifest.txt
jar ufm lib\zipfs.jar addToManifest.txt
ECHO All JAR manifest have been altered.
PAUSE
ECHO Signing all Applets...
jarsigner Applet_RFID.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner FingerPrintReader.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner jzebra.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner POSInterface.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\access-bridge-32.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\-keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\dnsns.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\dpuareu.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.admin.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.core.v1.13.0001.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.H2000.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.H6000IV.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.T20.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.T81.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.T81II.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.T82.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.T88V.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\epsonupos.trace.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\HWHydraSO.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\jaccess.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\jcl_editor.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\jpos113-controls.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\jpos113.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\jssc_qz.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\localedata.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\plugin.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\pos.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\pos.v3.0001.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\stario.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\starjavapos.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\sunec.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\sunjce_provider.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\sunmscapi.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\sunpkcs11.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\Symbol.RFID.API3.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\uposcommon.core.v1.13.0001.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\uposcommon.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\xercesImpl.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\xml-apis.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
jarsigner lib\zipfs.jar -keystore "C:\Certificate\YourCertificate.key" <keystoreName> -storepass <SecretKey>
ECHO All JAR files have been signed.
PAUSE

A: You have to disable the java temporary files
In windows:

*

*control panel

*java

*General Tab

*Temporary Internet File

*Settings button

*List item

*New Dialog : Temporary Files Settings dialog

*disable the option : keep temporary files on my computer.

A: I had a problem with Java Web Start, where some JAR files contained unsigned resources. I had to delete the unsigned resources from the JAR and then resign the JAR.

A: I had to uninstall all versions of Java, reinstall the latest version, clear the prompts, then add the website it was having as a trusted site. After that, the Java app loaded fine.

A: there is a simple solution that have just worked for me - unsign all jars.
Not the most elegant solution, since Oracle is trying to insist on signed code.


text:
Q: HTML Email looks fine in Litmus but broken in Outlook 2010 I have a table that when tested using Litmus, displays perfectly fine and displays like this for Outlook 2010 (logos blurred for obvious reasons):

However, when actually sent to the inbox of a Outlook 2010 user, Outlook bastardises it:

The code for this table is but I have no idea why this issue is happening or how to troubleshoot it, anyone got any ideas?:

                    This email was delivered to you

                    Click here to visit The website.

                    Unsubscribe: If you would prefer not to be contacted by #, please unsubscribe here.

                    Forward to a friend: If you would like to forward this email to a friend, please click here.

                    Our Privacy Statement.

                    © Copyright # 2014.

                    sdfsdff lorem ipsum.

                    sdfsdff lorem ipsumsdfsdff lorem ipsumsdfsdff lorem ipsumsdfsdff lorem ipsum sdfsdff lorem ipsum.

A: Please check if you have used any css into mail body


text:
Q: Disable user account in WSO2 Identity Server Is it possible to disable a user account in WSO2 Identity Server 5.0 after a certain period of inactivity? Is there any way to implement this using a REST or SAOP API?

A: i'm new on WSO2 Identity Server, but I would try this way:

*

*Create a scheduled job.
You can implement it as you want or, for example, you can use WSO2 Task Server features.

*The scheduled could call a web service, who implements these steps:

*

*read last login timestamp for each user in IS;

*calculate difference from last login timestamp e current timestamp;

*populate a list of users to disable;

*for each user to disable, call the WSO2 Identity Server Admin Services  to "disable operation".

I'don't find the "disable operation" implemented in IS, so i think you could realize a DISABLE status creating a role, called "USER_DISABLED", without login permission or try to remove login permission on the original role of the user.
As I said i'm new on WSO2 IS, but i would try this way.
Sorry for my english.
Bye
Vincenzo F.

A: You cannot directly disable the user account. what you can do is, you can disable user account by changing the permission of the user in the user group. In order to disable the login account You have to add the particular user to that user group. You can un-check it at the user permission tree.
Find the below steps to change the user permission:

*

*Login to WSO2 IS Management Console.

*Click on Configure to access the Configure menu.

*From the Configure menu, select Users and Roles.

*On the User Management page, click on the Roles link.

*Locate the role you want to edit, and click on the Permissions link
associated with it.

*On the Permissions of the Role page, deselect permissions assigned
to the role using the check-boxes.

*finally click on the Update button to save the alterations.


text:
Q: Dynamic OG meta data for Facebook I have a small web page that, every day, displays a one word answer - either Yes or No - depending on some other factor that changes daily.
Underneath this, I have a Facebook like button. I want this button to post, in the title/description, either "Yes" or "No", depending on the verdict that day.
I have set up the OG metadata dynamically using php to echo the correct string into the og:title etc. But Facebook caches the value, so someone sharing my page on Tuesday can easily end up posting the wrong content to Facebook.
I have confirmed this is the issue by using the Facebook object debugger. As soon as I force a refresh, all is well. I attempted to automate this using curl, but this doesn't seem to work.
$ch = curl_init();
$timeout = 30;
curl_setopt($ch, CURLOPT_URL, "http://developers.facebook.com/tools/lint/?url={http://ispizzahalfprice.com}");
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
echo $data;

Am I missing some easy fix here? Or do I need to re-evaluate my website structure to acheive what I am looking for (e.g. use two separate pages)?
Here's the page in case it's useful: http://ispizzahalfprice.com

A: Using two separate URL's would be the safe bet. As you have observed, Facebook does quite heavy caching on URL scrapes. You've also seen that you, as the admin of the App, can flush and refresh Facebook's cache by pulling the page through the debugger again.
Using two URL's would solve this issue because Facebook could cache the results all they want! There will still be a separate URL for "yes" and one for "no".


text:
Q: f.collection_select order by name how do I order this by name?
 <%= f.collection_select :carmodel_id_equals, Carmodel.all, :id, :name, :include_blank => true %>

I've looked in some search results in here but nothing worked.
p.s. this is a meta_search f.select form. Thanks.

A: you just have to order your search results from Carmodel.all by using order like this: Carmodel.order('name ASC').all
so if you put it all together it should look like:
<%= f.collection_select :carmodel_id_equals, Carmodel.order('name ASC').all, :id, :name, :include_blank => true %>
Read more in the awesome Rails Guide


text:
Q: Pattern module issues (NLP learning) I've been learning NLP text classification via book "Text Analytics with Python". It's required several modules to be installed in a virtual environment. I use Anaconda env. I created a blank env with Python 3.7 and installed required pandas, numpy, nltk, gensim, sklearn... then, I have to install Pattern. The first problem is that I can't install Pattern via conda because of a conflict  between Pattern and mkl_random.
(nlp) D:\Python\Text_classification>conda install -c mickc pattern
Solving environment: failed

UnsatisfiableError: The following specifications were found to be in conflict:
  - mkl_random
  - pattern
Use "conda info <package>" to see the dependencies for each package.

It's impossible to remove mkl_random because there're related packages: gensim, numpy, scikit-learn etc. I don't know what to do, I didn't find any suitable conda installations for Pattern that is accepted in my case. Then, I installed Pattern using pip. Installation was successful. Is it okay to have packages from conda and from pip at the same time?
The second problem, I think, is connected with the first one. I downloaded the book's example codes from https://github.com/dipanjanS/text-analytics-with-python/tree/master/Old-First-Edition/source_code/Ch04_Text_Classification, added brackets to Python 2.x 'print' functions and run classification.py
The program raised an exception:
Traceback (most recent call last):
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 609, in _read
    raise StopIteration
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "classification.py", line 50, in <module>
    norm_train_corpus = normalize_corpus(train_corpus)
  File "D:\Python\Text_classification\normalization.py", line 96, in normalize_corpus
    text = lemmatize_text(text)
  File "D:\Python\Text_classification\normalization.py", line 67, in lemmatize_text
    pos_tagged_text = pos_tag_text(text)
  File "D:\Python\Text_classification\normalization.py", line 58, in pos_tag_text
    tagged_text = tag(text)
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\en\__init__.py", line 188, in tag
    for sentence in parse(s, tokenize, True, False, False, False, encoding, **kwargs).split():
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\en\__init__.py", line 169, in parse
    return parser.parse(s, *args, **kwargs)
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 1172, in parse
    s[i] = self.find_tags(s[i], **kwargs)
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\en\__init__.py", line 114, in find_tags
    return _Parser.find_tags(self, tokens, **kwargs)
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 1113, in find_tags
    lexicon = kwargs.get("lexicon", self.lexicon or {}),
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 376, in __len__
    return self._lazy("__len__")
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 368, in _lazy
    self.load()
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 625, in load
    dict.update(self, (x.split(" ")[:2] for x in _read(self._path) if len(x.split(" ")) > 1))
  File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 625, in <genexpr>
    dict.update(self, (x.split(" ")[:2] for x in _read(self._path) if len(x.split(" ")) > 1))
RuntimeError: generator raised StopIteration

I don't understand what is happening. Is the exception raised because my installation with pip, or the problem is in the wrong or deprecated code in the book... and is it possible to install Pattern in conda with all other necessary packages.
Thank you in advance!

A: Switching to Python 3.6 solved this issue for me.
If you are using conda, first set up an environment, and specify that you want to use 3.6, and install any packages you need there.
conda create --name myenv python=3.6 pandas numpy gensim jupyter
conda activate myenv

For some reason, I didn't need to install Pattern directly.
Related Gensim explanation: https://github.com/RaRe-Technologies/gensim/issues/2438


text:
Q: How to include tooltip/popper in FullCalendar 5? I am trying to incorporate tooltip/popper into my Fullcalendar so that when I hover over an event it shows the full title (it is truncated in the calendar). I have tried eventDidMount and nothing happens when I place my cursor over the event (and no console errors). I have also tried eventRender (Tooltip in FullCalendar) and there is an error in the console log "main.min.js:6 Unknown option 'eventRender'".
I am using Bootstrap 5 (I do not know if that is relevant).
I am including:
<!-- Tooltip -->
<script src='https://unpkg.com/popper.js/dist/umd/popper.min.js'></script>
<script src='https://unpkg.com/tooltip.js/dist/umd/tooltip.min.js'></script>

I have copied the css from the example: Event tooltip with eventDidMount and Tooltip.js
/*Tooltip and popper */
.popper,
.tooltip {
  position: absolute;
  z-index: 9999;
  background: #FFC107;
  color: black;
  width: 150px;
  border-radius: 3px;
  box-shadow: 0 0 2px rgba(0,0,0,0.5);
  padding: 10px;
  text-align: center;
}
.style5 .tooltip {
  background: #1E252B;
  color: #FFFFFF;
  max-width: 200px;
  width: auto;
  font-size: .8rem;
  padding: .5em 1em;
}
.popper .popper__arrow,
.tooltip .tooltip-arrow {
  width: 0;
  height: 0;
  border-style: solid;
  position: absolute;
  margin: 5px;
}

.tooltip .tooltip-arrow,
.popper .popper__arrow {
  border-color: #FFC107;
}
.style5 .tooltip .tooltip-arrow {
  border-color: #1E252B;
}
.popper[x-placement^="top"],
.tooltip[x-placement^="top"] {
  margin-bottom: 5px;
}
.popper[x-placement^="top"] .popper__arrow,
.tooltip[x-placement^="top"] .tooltip-arrow {
  border-width: 5px 5px 0 5px;
  border-left-color: transparent;
  border-right-color: transparent;
  border-bottom-color: transparent;
  bottom: -5px;
  left: calc(50% - 5px);
  margin-top: 0;
  margin-bottom: 0;
}
.popper[x-placement^="bottom"],
.tooltip[x-placement^="bottom"] {
  margin-top: 5px;
}
.tooltip[x-placement^="bottom"] .tooltip-arrow,
.popper[x-placement^="bottom"] .popper__arrow {
  border-width: 0 5px 5px 5px;
  border-left-color: transparent;
  border-right-color: transparent;
  border-top-color: transparent;
  top: -5px;
  left: calc(50% - 5px);
  margin-top: 0;
  margin-bottom: 0;
}
.tooltip[x-placement^="right"],
.popper[x-placement^="right"] {
  margin-left: 5px;
}
.popper[x-placement^="right"] .popper__arrow,
.tooltip[x-placement^="right"] .tooltip-arrow {
  border-width: 5px 5px 5px 0;
  border-left-color: transparent;
  border-top-color: transparent;
  border-bottom-color: transparent;
  left: -5px;
  top: calc(50% - 5px);
  margin-left: 0;
  margin-right: 0;
}
.popper[x-placement^="left"],
.tooltip[x-placement^="left"] {
  margin-right: 5px;
}
.popper[x-placement^="left"] .popper__arrow,
.tooltip[x-placement^="left"] .tooltip-arrow {
  border-width: 5px 0 5px 5px;
  border-top-color: transparent;
  border-right-color: transparent;
  border-bottom-color: transparent;
  right: -5px;
  top: calc(50% - 5px);
  margin-left: 0;
  margin-right: 0;
}

My js:
eventDidMount: function(info) {
    var tooltip = new Tooltip(info.el, {
        title: info.event.title,
        //title: event.title, //tried this
        //title: title, //tried this
        //title: fc-event-title, //tried this
        placement: 'top',
        trigger: 'hover',
        container: 'body'
    });
},


text:
Q: Convert std string to ascii char and send through the serial port c++ I'm quite new to c++ and this is my problem:
I have a std::string and I want to convert each character to its Ascii symbol, put them into a unsigned char buffer and send all through the serial port. I know it can't be so clear so I 'll give an example:
std::string stringaStd = "010203";

I would like to send through the serial port the sequence:
'0' '1' '0' '2' '0' '3'

that should be equivalent to:
0x30 0x31 0x30 0x32 0x30 0x33

Hence, the chars of stringaStd have to be converted to Ascii and after that sent through the serial port.
Any idea for how to do that?
Thanks!

A: ASCII is 7-bit characters. There are extensions (ANSI character set, CP-1252, whatever) with 8 bits but pure ASCII does not utilize the most significant bit. Network transmission might make use of it as a parity flag for error detection/correction but I am drifting away from the main topic.
A char is by standard definition at least 8 bits wide, i.e., it is definitely capable of holding an ASCII character.
Retrieve single chars from the string using std::string::operator[] like in
stringaStd[x]

and, to obtain only the ASCII-relevant part, AND it with 0x7f:
stringaStd[x] & 0x7f

Usually, the unused bits in a char when representing an ASCII character are cleared but I don't think this is standardized anywhere.
This whole process can be mangled into a loop. Range checking can be performed using exceptions (std::string::at), C-string null terminators (std::string::c_str or, since C++11, also std::string::data), or iterators (range-based for-loop).
In addition, use the API provided to interact with the appropriate serial port and you're done.

A: If your compiler uses ASCII to encode character strings (which it almost certainly does; I mention this only for completeness) then the characters in a std::string object are already ASCII. There is no conversion needed. The character value '0', treated as a number, has the value 0x30. Try it:
char ch = '0';
std::cout << ch << ' ' << (int)ch << '\n';

To write those ASCII values one at a time to a port, just do it:
std::string text("012345");
for (int i = 0 ;i < text.size(); ++i)
    send_to_port(text[i]);

If you need an intermediate buffer, again, just do it:
unsigned char buf[80];
assert(text.size() <= 80);
std::copy(text.begin(), text.end(), buf);

Masking char values with 0x7f is wrong. If the string somehow has non-ASCII values (i.e., 8-bit values with the high bit set), masking will clear the high bit, producing a value in the range for valid ASCII characters, but the value won't represent anything meaningful.


text:
Q: Convert GeoJSON string to Elasticsearch Geometry I have a GeoJSON string like this
{
            "type": "Polygon",
            "coordinates": [
              [
                [
                  121.4,
                  33.99831528411953
                ],
                [
                  120.32770211588034,
                  33.09540949748297
                ],
                [
                  121.4,
                  32.20168471588049
                ],
                [
                  122.47229788411967,
                  33.09540949748297
                ],
                [
                  121.4,
                  33.99831528411953
                ]
              ]
            ]
          }

I want transform it to Elasticsearch Geometry or ShapeBuilder.
But I didn't find a convenient way.
Has anyone encountered similar problems?
Or have tool classe can do this.
Thank you very much

A: I find a solution like
 String valueAsString = mapper.writeValueAsString(value);

        GeometryParser parser = new GeometryParser(true, true, true);
        XContentParser contentParser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, valueAsString);
        contentParser.nextToken();
        Geometry geometry = parser.parse(contentParser);

but I dont know this is right or not.

A: Here is how you can do this:
// read your GeoJSON string from a file
String geojson = ...;

// parse the GeoJSON
JsonXContent geoJsonParser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, geojson);

// create a shape builder (of type PolygonBuilder since the GeoJSON represents a polygon)
PolygonBuilder shapeBuilder = (PolygonBuilder) ShapeBuilder.parse(geoJsonParser);


text:
Q: Android Offline MBtiles Working Sample I downloaded following source from here:
https://github.com/djcoin/MBTilesDroidSpitterExampleSimple
I am have map.mbtiles in the /sdcard/map.mbtiles
I am getting following error:
06-22 23:51:12.252: E/AndroidRuntime(29240): FATAL EXCEPTION: main

06-22 23:51:12.252: E/AndroidRuntime(29240): java.lang.NoClassDefFoundError: org.osmdroid.tileprovider.tilesource.XYTileSource
06-22 23:51:12.252: E/AndroidRuntime(29240):    at org.tilespitter.mapboxtiles.MBTilesOsmdroidExample.<init>(MBTilesOsmdroidExample.java:29)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at java.lang.Class.newInstanceImpl(Native Method)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at java.lang.Class.newInstance(Class.java:1319)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1982)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2092)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at android.app.ActivityThread.access$600(ActivityThread.java:133)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1203)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at android.os.Looper.loop(Looper.java:137)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at android.app.ActivityThread.main(ActivityThread.java:4808)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at java.lang.reflect.Method.invokeNative(Native Method)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at java.lang.reflect.Method.invoke(Method.java:511)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:794)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:561)
06-22 23:51:12.252: E/AndroidRuntime(29240):    at     dalvik.system.NativeStart.main(Native Method)

I am looking for a working Android MBTiles sample.  I am looking for a working android Offline MBtiles sample.  Where is the org.osmdroid.tileprovider.tilesource.XYTileSource class?  Can you provide me with a working OSMDroid offline MBtiles example?  OSMDroid has OSMMapTilePackager, OpenStreetMapViewer, GoogleWrapperSample, and others.  I want a specific samples with Offline MBtiles loaded.


text: Q: how to reset LiveData when user has navigated to another screen I am new to android and In my android project i am making an API call when user presses button to get OTP and if the response from server is successful i am navigating the user to another screen where he could submitt the OTP.problem arises when i presses back button ,since i am observing the livedata and that livedata is still in success state hence user goes back and immediately get navigated to the current screen(making it feel user stayed on same screen).Please help how can i solve this problem.


text:
Q: Xamarin MVVM Button Binding To Command Not Working Just started using Xamarin - been using PRISM with WPF for 10 years. Can't get binding for button commands working.  Binding Label to property works fine (Blah prop).  I set the BindingContext in code (in the VM ctor) (because I split up Views and ViewModels in different projects).
When I click the button in app the command handler never fires.  If I set the command on the button in code (uncomment last line of the VM ctor).
Anyone know why this is not working? am I missing something?  Do I need to use the ViewModelLocator and bind it in XAML?  thanks.
XAML (MainPage.xaml):
        <Label Text="{Binding Blah}" />

        <Button
        x:Name="rotateButton"
        Command="{Binding RotateCommand}"
        HorizontalOptions="Center"
        Text="Click to Rotate Text!"
        VerticalOptions="CenterAndExpand" />

XAML (MainPage.xaml.cs):
    public partial class MainPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    public Button RotateButton => rotateButton;

    public async void RotateLabel()
    {
        await label.RelRotateTo(360, 1000);
    }
}

VM (MainPageViewModel.cs):
    private string _blah;
    public MainPageViewModel(MainPage mainPage)
    {
        mainPage.BindingContext = this;
        RotateCommand = new Command(HandleRotateCommand,
            () => true);
        //if i uncomment this, the button fires.  not ideal obviously.
        //mainPage.RotateButton.Command = RotateCommand;
    }
    public ICommand RotateCommand { get; }

    public string Blah
    {
        get => _blah;
        set
        {
            _blah = value;
            OnPropertyChanged();
        }
    }

    private void HandleRotateCommand()
    {
        Debug.WriteLine("HandleRotateCommand");
        View.RotateLabel();
    }

A: The short answer
All you have to do (using the code as you shared) is to move the setting of the BindingContext to the end of your ViewModel constructor, like
public MainPageViewModel(MainPage mainPage)
{

    RotateCommand = new Command(HandleRotateCommand,
        () => true);
    //if i uncomment this, the button fires.  not ideal obviously.
    //mainPage.RotateButton.Command = RotateCommand;

    mainPage.BindingContext = this;
}

Explanation
The problem with your piece of code is that at the start of the ViewModel constructor you set the binding, and just after that you create the command. In that point the binding to the command is broken. That is why you have to move the setting of the BindingContext to the end, so that the binding is set on the created Command...


text:
Q: How to get the number value from a textfield I want to make a calculator. I have an array to store my value in it . I have two text fields (text1 and text2) where text1 refer to array[0] and text2 refer to array[1] .. when I insert number 1 in text1 and insert number 2 in text2 , then I get 3 as output but when I insert number 12 in text1 and I insert number 22 in text2 then I still get output 3 , this means that the calculator add 1+2 but not 12+22 .. How can I get the whole value in text1 and text2 to add them together? I mean I want the output should be 12+22=34 ...thanks
stack class
    int[] array = new int[4];
public enum Operation {
        PLUS
    }

    public void CalculateSign(Operation op) {
        switch (op) {
        case PLUS:
            result = (array[0] + array[1]);
            //array[0] = result;
            System.out.println(array[0]);
            System.out.println(array[1]);
            break;
            }

public void Number(int nbr) {

        array[0] = nbr;
    }

calculator class
TextField text1 = new TextField();
TextField text2 = new TextField();

plusButton.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {

                if (event.getSource() == plusButton) {
                    stack.CalculateSign(Stack.Operation.PLUS);
                    text1.setText(Integer.toString(stack.result));

                }
            }

        });

one.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {

                if (event.getSource() == one) {

                    stack.Number(1);                                                                        text1.setText(text1.getText()+String.valueOf(stack.array[0]));

                }
            }

        });

        two.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {

                if (event.getSource() == two) {
                    stack.Number(2);
                    text1.setText(text1.getText()+String.valueOf(stack.array[0]));

                }
            }

        });

A: Your Number(int nbr) method sets the array cells to its parameter value. In your EventHandlers for your two TextFields you have hard-coded Number(1) and Number(2). Ergo, you will always add 1 and 2, regardless of the actal contents of text1 and text2.


text:
Q: AngularJS validating my form After validating my form, I need to submit it.
I need to submit the form to another mocked API endpoint which returns true or false depending on whether the answer provided was correct, and display this response in the UI.
Is it possible to implement this to archive it? https://docs.angularjs.org/api/ng/service/$http
Plunker Demo
html:
<my-form ng-app="CreateApp" ng-controller="mainController">
  <form ng-submit="submitForm()" novalidate>
      <fieldset>

          {{field.label}}
          <input ng-if="field.type != 'radio'" ng-required="{{field.required}}" value="{{options.value}}" type="{{field.type}}">

              <input type="{{field.type}}"
                     ng-model="richestClub"
                     value="{{option.value}}">{{option.label}}

          <form-error ng-show="{{!!field.errorMessages.required}}">{{field.errorMessages.required}}</form-error>
          <form-error ng-show="{{!!field.errorMessages.invalid}}">{{field.errorMessages.invalid}}</form-error>

      </fieldset>

      <button type="button" ng-click="onValidate(); return false;"> Validate</button>
      <button type="submit" ng-disabled="userForm.$invalid"> Submit </button>
    </form>

</my-form>

JS controller:
var myApp=angular.module('CreateApp', []);

myApp.controller('mainController', function($scope, $http) {
  $http.get('form.json').success(function(response) {
    $scope.result = response;
    console.log($scope.fields);
  });

  $http.get('form.json').success(function(response) {
    $scope.result = response;
    var fields = response.fields;
    $scope.richestClub = fields.answer.options[0].value;
    console.log($scope.richestClub);
    console.log($scope.fields);
  });

});

A: This is definitely possible. However your code has several errors.
You use userForm as the form variable but don't specify it. It should be like
<form name="userForm">

in order to access it in JS.
The same for the fields - if you want to access their errors you should provide their name
like <input type="" name="{{field.name}}" /> and then you can access validation results through "userForm[field.name]".
Add callback to submit button: <button type="submit" ng-disabled="userForm.$invalid" ng-click="onSubmit(userForm)"> Submit </button>


text:
Q: Compile multiple **changed** source files at once in GNU make I know there have been several questions with similar titles but none seem to provide an answer to what I need (correct me if I'm wrong).
Consider this makefile:
SOURCES=file1.cpp file2.cpp file3.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=myprog

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CXX) -o $@ $(OBJECTS)

file1.o: file1.cpp file1.h
file2.o: file2.cpp file2.h file1.h
file3.o: file3.cpp

.cpp.o:
    $(CXX) $(CXXFLAGS) -c -o $@ $<

If I change file1.h, the following is run:
g++ -c -o file1.o file1.cpp
g++ -c -o file2.o file2.cpp
g++ -o myprog file1.o file2.o file3.o

What I would like to have is:
g++ -c file1.cpp file2.cpp
g++ -o myprog file1.o file2.o file3.o

(I know I can't specify object output directory with GCC, but this I can live with; it should be possible to work around with some cd commands.)
In nmake, this is done with a double-colon inference rule (so-called called "batch-mode rule"). Basically, it groups the inference rules (e.g. ".obj.cpp:") for multiple targets and invokes the compiler for all dependencies instead of once per file. The $< variable gets the list of dependencies instead of just the first one.
Right now we're using parallel building (make -j) but it has its own issues, and VC++ compiler works much better in one-invocation mode so I'd prefer using that.

A: I don't see why you want this effect, but here's how to get it (in GNUMake):
SOURCES=file1.cpp file2.cpp file3.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=myprog

all: $(EXECUTABLE)

$(EXECUTABLE): $(SOURCES)
    $(CXX) $(CXXFLAGS) -c $?
    $(CXX) -o $@ $(OBJECTS)

EDIT:
I'm surprised that that solution works -- there's something wrong with my idea of what Make does -- but I don't think it'll work in your case, with header dependencies, without the following kludge. (There are one or two other approaches that might work, if this doesn't pan out.)
SOURCES=file1.cpp file2.cpp file3.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=myprog

all: $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS)
    $(CXX) -o $@ $(OBJECTS)

file1.cpp: file1.h
file2.cpp: file2.h file1.h

$(SOURCES):
    @touch $@

$(OBJECTS): $(SOURCES)
    $(CXX) $(CXXFLAGS) -c $?
    @touch $(OBJECTS)

A: You can make GNUmake do what you want by collecting the files to be rebuilt in the build rule and then actually building them when you link:
SOURCES=file1.cpp file2.cpp file3.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=myprog

all: $(EXECUTABLE)

.PHONY: build_list

build_list:
        -rm -f build_list

$(OBJECTS): %.o: %.cpp | build_list
        echo $< >> build_list

$(EXECUTABLE): build_list $(OBJECTS)
        if [ -r build_list ]; then $(CXX) $(CXXFLAGS) -c `cat build_list`; fi
        $(CXX) -o $@ $(OBJECTS)

file1.o: file1.h
file2.o: file2.h file1.h


text:
Q: Seleccionar solo un checkbox de una fila por tabla html javascript Tengo un problema espero que me puedan ayudar, resulta que tengo una tabla que genero mediante un foreach en php el cual me trae información de facturas cargadas, lo que requiero es hacer que mediante checkbox pueda indicarle si la quiero autorizar o rechazar, el problema es que solo requiero que se quede marcada una opción para cada fila de la tabla, ya se que eso se puede realizar con un radio button, pero no lo hago así ya que si el usuario no marca ninguna de las casillas el estatus de la factura no debe verse afectado y con el radio button siempre se queda marcada una de las dos opciones.
el codigo de mi html es el siguiente:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
    <link rel="stylesheet" href="css/font-awesome.css">
    <link rel="stylesheet" href="css/autorizafacturas.css">
    <link rel="stylesheet" href="css/jquery-ui.css">
    <link rel="icon" href="img/gota.ico" type="image/x-icon"/>
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Autoriza Facturas</title>

Autorizacion de Facturas

                Cerrar sesion

                Regresar al Menu

            <form class="fechas" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" name="fechas" id="fechas">
                Fecha Inicial:
                <input type="date" name="date" class="tcal" id="fechaini" value="" />
                Fecha Final:
                <input type="date" name="date2" class="tcal" id="fechafin" value="" />
                Proveedor:
                <input type="text" name="proveedor" id="proveedor">
                <input type="submit" value="Buscar" name="fechas" id="fechasb">
            </form>
            <?php if(!empty($errores)):?>

                    <?php echo $errores; ?>

            <?php endif;?>
            <?php if(!empty($consulta)):?>

                <form  action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" id="facturas">

                        Acuse
                        Proveedor
                        Archivo
                        Orden
                        Serie
                        Folio
                        Fecha
                        Ver Factura
                        Ver Comprobante Entrega
                        Autorizar
                        Rechazar

                    <?php foreach($resultado as $fila): ?>
                        <div class="formgroup<?php echo $i?>">

                            <?php echo '' . $fila['cfi_acu'] . '	'; ?>
                            <?php echo '' . $fila['usu_nom'] . '	'; ?>
                            <?php echo '' . $fila['cfi_nom'] . '	'; ?>
                            <?php echo '' . $fila['cfi_oc'] . '	'; ?>
                            <?php echo '' . $fila['cfi_ser'] . '	'; ?>
                            <?php echo '' . $fila['cfi_fol'] . '	'; ?>
                            <?php echo '' . $fila['cfi_fec_add'] . '	'; ?>
                            <a target="_blank" href="localhost/almacen/ingresos/<?php echo  $fila['cfi_nom']?>.pdf">
                            <a target="_blank" href="localhost/almacen/ingresos/<?php echo  $fila['cfi_nom'].'-OE'?>.pdf">
                            <input onclick="uncheck()" type="checkbox" id="autorizar" name="autorizar[]" value="<?php echo $fila['cfi_acu']?>">
                            <input onclick="uncheck()" type="checkbox" id="rechazar" name="rechazar[]" value="<?php echo $fila['cfi_acu']?>">

                    <?php endforeach;?>

                <input class="eliminar" type="submit" value="Autorizar Facturas" name="autorizacion" id="autorizacion">
                </form>
            <?php endif; ?>
            <?php if(!empty($autoriza)):?>

                    <?php echo $autoriza; ?>

            <?php endif;?>

function uncheck(){
    var checkbox1 = document.getElementById('autorizar');
    var checkbox2 = document.getElementById('rechazar');

   checkbox1.onclick = function(){
   if(checkbox1.checked != false){
   checkbox2.checked =null; }
    }
   checkbox2.onclick = function(){
   if(checkbox2.checked != false){
   checkbox1.checked=null;
    }
    }
   }

A: Hola a todos actualizando, ya logre resolverlo, mi problema era que estaba colocando el mismo id a todos los input tipo check box lo que hice fue colocarles un id diferente a cada uno apoyandome con el id de la factura y pasarle a la funcion uncheked() dos argumentos que son los id de los checkbox que quiero seleccionar.
<?php foreach($resultado as $fila): ?>

                            <?php echo '' . $fila['cfi_acu'] . '	'; ?>
                            <?php echo '' . $fila['usu_nom'] . '	'; ?>
                            <?php echo '' . $fila['cfi_nom'] . '	'; ?>
                            <?php echo '' . $fila['cfi_oc'] . '	'; ?>
                            <?php echo '' . $fila['cfi_ser'] . '	'; ?>
                            <?php echo '' . $fila['cfi_fol'] . '	'; ?>
                            <?php echo '' . $fila['cfi_fec_add'] . '	'; ?>
                            <a target="_blank" href="http://proveedores-chemtreat.com.mx/chemtreat/almacen/ingresos/<?php echo  $fila['cfi_nom']?>.pdf">
                            <a target="_blank" href="http://proveedores-chemtreat.com.mx/chemtreat/almacen/ingresos/<?php echo  $fila['cfi_nom'].'-OE'?>.pdf">
                            <input onclick="uncheck('autorizar'+'<?php echo $fila['cfi_acu']?>','rechazar'+'<?php echo $fila['cfi_acu']?>')" type="checkbox" id="autorizar<?php echo $fila['cfi_acu']?>" name="autorizar[]" value="<?php echo $fila['cfi_acu']?>">
                            <input onclick="uncheck('autorizar'+'<?php echo $fila['cfi_acu']?>','rechazar'+'<?php echo $fila['cfi_acu']?>')" type="checkbox" id="rechazar<?php echo $fila['cfi_acu']?>" name="rechazar[]" value="<?php echo $fila['cfi_acu']?>">

                    <?php endforeach;?>

function uncheck(autorizar, rechazar){
    var checkbox1 = document.getElementById(autorizar);
    var checkbox2 = document.getElementById(rechazar);
   checkbox1.onclick = function(){
   if(checkbox1.checked != false){
   checkbox2.checked =false; }
    }
   checkbox2.onclick = function(){
   if(checkbox2.checked != false){
   checkbox1.checked=false;
    }
    }
   }


text:
Q: SSRS 2008 & Column Headers As you may be aware there is a peculiar situation with the display of column headers in SSRS2008... i.e. you need to dig around a bit to get them to repeat on every page.
http://blogs.msdn.com/b/robertbruckner/archive/2008/10/13/repeat-header-and-visible-fixed-header-table.aspx
All of the examples I've seen rely on some kind of grouping going on. I'm not using groups in my report. Any idea how I can get the headers of a tablix to appear on each new page.
Many thanks.

A: I suggest including a dummy field in the dataset, set to a constant value throughout the report. Group at the top level on the dummy field, move the tablix column headings into the group header and follow the rest of the steps in the MSDN blog.

A:
select Advance Mode in Group Properties
Select Static Group from Row Group
in Static Group Properties,
set RepeatOnNewPage as True
and additionally KeepWithGroup as After
by setting this,
you can view row header in each and every pages.
thanks.