text:
Q: IOSurface - IOS Private API - Capture screenshot in background I want to capture a screenshot from a background service. Private API is just fine as I don't need to submit to app store. I have already tried UIGetScreenImage and it does not work from background app.
I am using following code which I got from SO. IOSurfaceCreate returns null to me. Any help appreciated.
CFMutableDictionaryRef dict;
        IOSurfaceRef screenSurface = NULL;

        char pixelFormat[4] = {'A','R','G','B'};
        dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

        uint32_t width ;
        uint32_t height;
        void *pitch;
        void *bPE;
        void *size;
        CFDictionarySetValue(dict, kIOSurfaceIsGlobal, kCFBooleanTrue);
        CFDictionarySetValue(dict, kIOSurfaceBytesPerRow, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pitch));
        CFDictionarySetValue(dict, kIOSurfaceBytesPerElement, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bPE));
        CFDictionarySetValue(dict, kIOSurfaceWidth, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width));
        CFDictionarySetValue(dict, kIOSurfaceHeight, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height));
        CFDictionarySetValue(dict, kIOSurfacePixelFormat, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, pixelFormat));
        CFDictionarySetValue(dict, kIOSurfaceAllocSize, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &size));

        IOSurfaceRef destSurf = IOSurfaceCreate(dict);
        IOSurfaceAcceleratorRef outAcc;
        IOSurfaceAcceleratorCreate(NULL, 0, &outAcc);

        CFDictionaryRef ed = (__bridge CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys: nil];
        IOSurfaceAcceleratorTransferSurface(outAcc, screenSurface, destSurf, ed, NULL);
        uint32_t aseed;
        IOSurfaceUnlock(screenSurface, kIOSurfaceLockReadOnly, &aseed);

        CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, IOSurfaceGetBaseAddress(destSurf), (width*height*4), NULL);
        CGImageRef cgImage=CGImageCreate(width, height, 8, 8*4, IOSurfaceGetBytesPerRow(destSurf), CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little, provider, NULL, YES, kCGRenderingIntentDefault);
        UIImage *image = [UIImage imageWithCGImage: cgImage];
        UIImageWriteToSavedPhotosAlbum(image, self_object, nil, nil);
        CGImageRelease(cgImage);
        CFRelease(destSurf);

A: After combining code from 2 places, I was able to save photo to photo album (with my application in background).
IOSurfaces - Artefacts in video and unable to grab video surfaces
https://github.com/tomcool420/SMFramework/blob/master/SMFScreenCapture.m
Please try out and let me know if it works for you.
-(void)SavePhoto
{
    IOMobileFramebufferConnection connect;
    kern_return_t result;
    IOSurfaceRef screenSurface = NULL;

    io_service_t framebufferService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleH1CLCD"));
    if(!framebufferService)
        framebufferService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleM2CLCD"));
    if(!framebufferService)
        framebufferService = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleCLCD"));

    result = IOMobileFramebufferOpen(framebufferService, mach_task_self(), 0, &connect);

    result = IOMobileFramebufferGetLayerDefaultSurface(connect, 0, &screenSurface);

    uint32_t aseed;
    IOSurfaceLock(screenSurface, kIOSurfaceLockReadOnly, &aseed);
    uint32_t width = IOSurfaceGetWidth(screenSurface);
    uint32_t height = IOSurfaceGetHeight(screenSurface);
    //int m_width = 320;
    //int m_height = 480;
    CFMutableDictionaryRef dict;
    int pitch = width*4, size = width*height*4;
    int bPE=4;
    char pixelFormat[4] = {'A','R','G','B'};
    dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(dict, kIOSurfaceIsGlobal, kCFBooleanTrue);
    CFDictionarySetValue(dict, kIOSurfaceBytesPerRow, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pitch));
    CFDictionarySetValue(dict, kIOSurfaceBytesPerElement, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bPE));
    CFDictionarySetValue(dict, kIOSurfaceWidth, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &width));
    CFDictionarySetValue(dict, kIOSurfaceHeight, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &height));
    CFDictionarySetValue(dict, kIOSurfacePixelFormat, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, pixelFormat));
    CFDictionarySetValue(dict, kIOSurfaceAllocSize, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &size));

    IOSurfaceRef destSurf = IOSurfaceCreate(dict);

    void* outAcc;
    IOSurfaceAcceleratorCreate(NULL, 0, &outAcc);

    IOSurfaceAcceleratorTransferSurface(outAcc, screenSurface, destSurf, dict, NULL);

    IOSurfaceUnlock(screenSurface, kIOSurfaceLockReadOnly, &aseed);
    CFRelease(outAcc);

    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, IOSurfaceGetBaseAddress(destSurf), (width * height * 4), NULL);
    CGImageRef cgImage=CGImageCreate(width, height, 8,
                                     8*4, IOSurfaceGetBytesPerRow(destSurf),
                                     CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst |kCGBitmapByteOrder32Little,
                                     provider, NULL,
                                     YES, kCGRenderingIntentDefault);
    UIImage *img = [UIImage imageWithCGImage:cgImage];
    UIImageWriteToSavedPhotosAlbum(img, self, nil, nil);

    // MOST RELEVANT PART OF CODE

    //CVPixelBufferCreateWithBytes(NULL, width, height, kCVPixelFormatType_32BGRA, IOSurfaceGetBaseAddress(destSurf), IOSurfaceGetBytesPerRow(destSurf), NULL, NULL, NULL, &sampleBuffer);
}


text:
Q: Magento - Logout when browser close User is logging into magento (without checking Remember Me option) and closes the browser without logging out from magento system. Now if the user opens a browser window again, it should be logged out. How do I do that in magento?

A: In PHP,
session_set_cookie_params(0);

Normally a cookie lifetime of "0" means "when the browser exits".
You can set the cookie lifetime form magento backend but keep in mind that this will also affect the session lifetime of the admin panel. So if you log in to the admin panel and you don't use it for a while, you'll be automatically logged out after the cookie lifetime expires.
Frontend (session) cookie
In Magento, the 'frontend' cookie gets set right before the current action is being dispatched.
Have a look at Mage_Core_Controller_Varien_Action::preDispatch().
Session start
Looking into preDispatch():
Mage::getSingleton('core/session', array('name' => $namespace))->start();
Which (if not overridden) finally maps to
Mage_Core_Model_Session_Abstract_Varien::start()
This is the place where all the standard session gets initialized and that includes cookie settings by using session_set_cookie_params.
Revalidation
Also you need to be aware that the constructor calls revalidateCookie() while instantiating the core session:
Mage_Core_Model_Session_Abstract_Varien::init()

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I force a key release event for fn+arrows (home,end,pgup,pgdn) This is the same problem asked before, but the "solution" was along the lines of "the problem went away after an update and reboot" which was purely serendipitous, as I tried installing the same distro version with updates and nothing changed. The problem was left unaddressed specifically.
After two weeks now of surfing for answers, I think I've correctly narrowed the problem but I'm too much of a noob to figure out how to code the solution.
Can anyone help please?

*

*I think the problem originates in the boot (BIOS), but I don't know how to change it (or really want to risk it from what I've read). Therefore, the solution could be ...

*A way to force a release event for the key presses. This is where I get stuck. As 18.04 has replaced "keymap" files with "hwdb" and "rules" files in the /etc/udev directory, I've tried all sorts of permutations of adding lines in newly created file 70-keyboard-force-release.hwdb and the same as a .rules file but all to no avail.
SHOWKEY reveals the scan and key codes, I just don't know what to do with them. I've tried using other matched pairs as templates, but I can't figure it out.
Can someone help me figure out the right code?
DESCRIPTION: I just installed LUBUNTU 18.04 LTS x86_64 on a brand-new Dell Inspiron 11-3162 but the "Home | End | PgUp | PgDn" functionality does not work.
On this particular keyboard you have to hit Fn+LeftArrow for Home, or Fn+RightArrow for End, Fn+UpArrow for PgUp and Fn+DownArrow for PgDn. The crazy part is the first time I use one of these functions it works. But if I try and go "home" or "end" a second time, nothing happens. I have to reboot to be able to do it again for the first time, and then nothing the second time.
Also, the Function key does work with other features ... for example the Fn+F2 and F3 de/increase the volume; Fn+F12 brightens the screen ; Fn+F1 mutes the sound.
MORE INFO: I forgot to mention my distro: Lubuntu 18.04 on an Inspiron 11-3162 with keyboard.
Keyboard description printout:

THE PROBLEM: This is a post of this problem with the "non-solution" I described. Very good description: Dell Inspiron 11-3162 Home | End | PgUp | PgDn keys not working
IS IT BIOS? Another user with similar problem but makes me think it's BIOS (due to comments): Fn key sticks down
BIOS OR GRUB? Another user with similar problem but makes me think it's BIOS or GRUB due to comments; I tried the solutions here to no avail: Getting function keys working on Samsung RV510 notebook
FAILED SOLUTION: This is what I consider the closest attempt but I cannot get it to work. https://github.com/arduino/dfu-utils-cross/blob/master/eudev-3.1.5/hwdb/60-keyboard.hwdb
There is something similar to it at: https://www.dell.com/community/Linux-General/Dell-Inspiron-3179-keyboard-not-sends-KEY-RELEASE-events-key-up/td-p/5114299
I tried:
IN etc/udev/hwdb:
evdev:atkbd:dmi:bvn*:bvr*:bd*:svnDell*:pn*Inspiron 11-3162:pvr*
KEYBOARD_KEY_c9=!pageup
KEYBOARD_KEY_d1=!pagedown
KEYBOARD_KEY_c7=!home
KEYBOARD_KEY_cf=!end

evdev:atkbd:dmi:bvn*:bvr*:bd*:svnDell*:pn*
KEYBOARD_KEY_0xe0 0x49=!pageup
KEYBOARD_KEY_0xe0 0x51=!pagedown
KEYBOARD_KEY_0xe0 0x47=!home
KEYBOARD_KEY_0xe0 0x4f=!end

evdev:atkbd:dmi:bvn*:bvr*:bd*:svnDell*:pn*
KEYBOARD_KEY_0x49=!pageup
KEYBOARD_KEY_0x51=!pagedown
KEYBOARD_KEY_0x47=!home
KEYBOARD_KEY_0x4f=!end

evdev:atkbd:dmi:bvn*:bvr*:bd*:svnDell*:pn*
KEYBOARD_KEY_0x49=!104
KEYBOARD_KEY_0x51=!109
KEYBOARD_KEY_0x47=!102
KEYBOARD_KEY_0x4f=!107

IN /etc/udev/rules.d:
evdev:atkbd:dmi:bvn*:bvr*:bd*:svnDell*:prn*
KEYBOARD_KEY_c9=!104
KEYBOARD_KEY_d1=!109
KEYBOARD_KEY_c7=!102
KEYBOARD_KEY_cf=!107

Almost everything else, I've put below in case any of the info helps you. As a Linux-infant, I found it helpful, but maybe I'm just chasing my tail in circles. I'm thinking I need to take a course somewhere but that's another topic. Anyway, here's more stuff I tried:
FAILED SOLUTION: I tried the solution here but I'm so illiterate, I'm not sure if I even translated the "solution" correctly. https://github.com/lu-zero/udev/blob/master/src/keymap/95-keyboard-force-release.rules
I tried: Edit /usr/lib/udev/rules.d/70-keymap.rules, add following line to the other Samsung specific lines
ACTION=="remove", GOTO="force_release_end"
SUBSYSTEM!="serio", GOTO="force_release_end"
KERNEL!="serio*", GOTO="force_release_end"
DRIVER!="atkbd", GOTO="force_release_end"

ENV{DMI_VENDOR}=="[iI][nN][sS][pP][iI][rR][oO][nN]*", ATTR{[dmi/id]product_name}=="11-3162*", RUN+="keyboard-force-release.sh $devpath Inspiron 11-3162"

LABEL="force_release_end"

FAILED SOLUTION: This was another similar article that I tried to use for another solution to no avail. http://natjohan.info/linux-on-samsung-np900x3c.html
FAILED SOLUTION: Here's another solution I tried called xdotool. https://unix.stackexchange.com/questions/60007/how-to-force-release-of-a-keyboard-modifiers/64716 I couldn't get anything to work after trying:
sudo xdotool keyup
sudo xdotool keyup --clearmodifiers
sudo xdotool key --clearmodifiers
sudo xdotool --clearmodifiers

FAILED SOLUTION: Trying to do something with keymap was a waste I learned because it has been replaced with /etc/udev/hwdb and /etc/udev/rules, but I tried to use some info in this article to come up with a solution to no avail: https://ask.fedoraproject.org/en/question/37598/how-to-create-custom-keymaps-now-that-libudevkeymap-is-gone/
BACKGROUND: This was one of the most helpful articles for me but I don't know enough to come up with the right code still.
BACKGROUND: Since my Linux experience totals all of about 3 weeks after being a Windows slave since DOS-days, I found the following articles that are somewhat specific to the problem helpful.
BACKGROUND: I used something called showkey to show key codes that showed the presses without the release:
showkey output:

You can see how the first press of the key presses but since there is no release event, it goes on, until I hit any other key. The order of the key press attempts is fn+left arrow (home, code 102), fn+right arrow (end, code 107), fn+up arrow (pgup, code 104), and fn+down arrow (pgdn, code 109). The bottom of the page output is for pressing only the arrows to show that they have different codes and that they have release events right after the press event. In the same order above (left, right, up, down), the codes are 105,106,103,108 (which is the same ass what evtest below shows)
BACKGROUND: I used something called evtest to show key codes and events: The order of the key presses are fn+left arrow (home, code 105), fn+right arrow (end, code 106), fn+up arrow (pgup, code 103), and fn+down arrow (pgdn, code 108),
Evtest output:

MORE INFO: After watching the ytube video: "3.3: Events (mousePressed, keyPressed) - Processing Tutorial" by The Coding Train, perhaps it's important for me to specify that I really need this fn+arrow functionality for using home, end, pgup, pgdn in Excel and Word. Though it would be nice to work in  things like my file manager, synaptics, the internet, and everywhere else, my priority is in Excel and Word.
INFO UPDATE: I forgot to mention another reason I think this might be a BIOS problem is that my Inspiron 11-3162 has a certified Ubuntu release 14.04, but the BIOS for that is 1.0and mine is 2.2. I tried installing that distro, but to no avail. I also read somewhere that the BIOS contains instructions for hardware including the keyboard. The IT guy where I work (Emory Univ) told me that it's possible that the BIOS either doesn't send a key release for the fn + arrows because Windows doesn't need it. He also told me it's possible that BIOS doesn't load properly if it detects a non-Windows OS (thanks Microsoft for intentionally making it harder to break the slave chains of Windows)
INFO UPDATE: Sorry for these frequent updates, but I do them in the spirit of hoping that they will help someone out there in the Linux ommunity ... esp as I am still trying to solve this problem myself. Anyway, here is a link to someone who is much more advanced than I (not hard to be) who has the same problem and who tried many of the things that I have - also to no avail.

A: Faced exactly the same problem on Lubuntu 20.04. And I'm writing this to make known what worked for me (thanks to https://www.dell.com/community/Linux-General/Dell-Inspiron-3179-keyboard-not-sends-KEY-RELEASE-events-key-up/m-p/5114301/highlight/true#M15475)
Firstly, lot of useful info could be obtained from the documentation in the /lib/udev/hwdb.d/60-keyboard.hwdb file. It's here where I got to know about "AT Keyboard" and a "force-release" list of scan codes maintained by the AT Keyboard (to make the driver synthesize a release event, when the same is not to be expected from the hardware).
The actual changes made:

*

*Created a file /etc/udev/hwdb.d/70-keyboard.hwdb, with the below content in it:

### for Dell Inspiron 11-3168

evdev:atkbd:dmi:bvn*:bvr*:bd*:svnDell*:pnInspiron*3168:pvr*
 KEYBOARD_KEY_c7=!home                              # Fn+Left Home
 KEYBOARD_KEY_cf=!end                               # Fn+Right End
 KEYBOARD_KEY_c9=!pageup                            # Fn+Up Page Up
 KEYBOARD_KEY_d1=!pagedown                          # Fn+Down Page Down

*Ran the below commands to activate the changes:

# systemd-hwdb update
# udevadm trigger --verbose /dev/input/event4

*Reboot (although not sure if this is actually required)

Hope this helps!

A: I think there are 2 ways of doing it:

*

*Using command line :
a) Get the output of your keymap xkbcomp -xkb $DISPLAY xkbmap and locate the keys you intend to interchange
b) Then interchange with  code xcape -e 'Caps_Lock=Escape' (Caps_Lock and Escape is given as example)

*Using GUI application:
a) Install the app from the repo sudo apt install xbindkeys xbindkeys-config
b) Launch xbindkeys-config GUI and alter accordingly.
Hope this helps


text:
Q: Create a maven webapp project using the eclipse kelper, I got an eclipse error I have a problem, use Eclipse-jee-kelper to create Maven Project, my step is new/Maven Project/maven-archetype-webapp/naming/finish, I got a Failed to create project "test" error, as follows: Could not calculate build plan: Plugin org.apache.maven.plugins:maven-war-plugin:2.1.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-war-plugin:jar:2.1.1
My environment is: Windows 7 64bit, JDK 1.7, eclipse Jee kelper, Maven 3.1.1
This may be a stupid question, but has been entangled me all morning.
Kindly advise!
Thanks in advance!

I have to close this problem, because I found the answer from
Spring's Forum

A: The same error appears to me. I solved it by updating maven and checking the option "Force update of Snapshots/Releases" in Eclipse. this clears all errors.
So right click on project -> Maven -> update project, then check the above option -> Ok.
Hope this helps you.

A: My solution is:
1. Windows-->Preferences-->maven--> user settings-->add
your maven directory/conf/ settings.XML   -->apply.
2. Next , installations -->add  -->your maven directory -->apply
After the two steps, maven test, or maven update project success.


text:
Q: How can I save a tif file without loosing the colors from a bytes array? I need to save a byte array of a tif image using JAI, I got my tif bytes array from gdal. I have the following code:
 BufferedImage bufferedImage = new BufferedImage( fullWidthSize/2, fullHeightSize/2, BufferedImage.TYPE_BYTE_BINARY);
 WritableRaster raster = bufferedImage.getRaster();
 raster.setDataElements(0, 0, fullWidthSize/2, fullHeightSize/2, bytes);

 TIFFEncodeParam params = new TIFFEncodeParam();
 params.setCompression( TIFFEncodeParam.COMPRESSION_NONE );
 String filenametiff = "/mnt/hdfs/user/hdfs/inImage/haw2_smallJAI.tif";
 JAI.create("filestore", bufferedImage, filenametiff, "TIFF", params);

but unfortunately it saves the tif image but in gray scale, I also tried TYPE_BYTE_INDEXED but it saves the image with strange colors sort of cloudy, and by using TYPE_CUSTOM I get the following error:
java.lang.IllegalArgumentException: Unknown image type 0
can you please provide me some guidance so the image can be written correctly?
P.S. The reason why I am not using gdal to persist the image is because somehow it is not being able to write in hdfs, with a "_tiffSeekProc:Operation not supported" message,  I did mount hdfs using FUSE.

A: This was slightly too long for a comment, sorry. ;-)
Here's some sample code, should be properly commented to help you understand what it does. Had fun writing it...
What it does, is creating and displaying 6 images (of random noise). There will be 3 different images, each created in two different ways. 4 will use a banded model and 2 interleaved model. For the banded models, it shows how to create them, both using single and multidimensional arrays.
import java.awt.Point;
import java.awt.Transparency;
import java.awt.Window;
import java.awt.color.ColorSpace;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BandedSampleModel;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.PixelInterleavedSampleModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.Arrays;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class BufferedImageTester {
    public static void main(String[] args) {
        // Part I
        // Dimensions, number of bands and other setup
        int width = 300;
        int height = 200;
        int bands = 3; // 4 works too, if you want alpha
        int bandSize = width * height;
        Point origin = new Point(0, 0);

        // Create backing data for single array banded model
        byte[] singleData = new byte[bandSize * bands];
        int[] singleBankIndices = createIndices(bands, 0, 0); // 0, 0, 0
        int[] singleBandOffsets = createIndices(bands, 0, bandSize); // 0, bandSize, 2 * bandSize

        // Create buffer for single array
        DataBufferByte singleBuffer = new DataBufferByte(singleData, singleData.length, 0);

        // Create raster directly from buffer
        WritableRaster bandedRaster1 = Raster.createBandedRaster(singleBuffer, width, height, width, singleBankIndices, singleBandOffsets, origin);
        System.out.println("bandedRaster1: " + bandedRaster1);

        // Create raster from sample model and buffer
        BandedSampleModel singleModel = new BandedSampleModel(DataBuffer.TYPE_BYTE, width, height, width, singleBankIndices, singleBandOffsets);
        WritableRaster bandedRaster2 = Raster.createWritableRaster(singleModel, singleBuffer, origin);
        System.out.println("bandedRaster2: " + bandedRaster2);

        // Create backing data for multiple arrays banded model
        byte[][] multiData = new byte[bands][bandSize];
        int[] multiBankIndices = createIndices(bands, 0, 1); // 0, 1, 2
        int[] multiBandOffsets = createIndices(bands, 0, 0); // 0, 0, 0

        // Create buffer for multiple arrays
        DataBufferByte multiBuffer = new DataBufferByte(multiData, bandSize, multiBandOffsets);

        // Create raster directly from buffer
        WritableRaster bandedRaster3 = Raster.createBandedRaster(multiBuffer, width, height, width, multiBankIndices, multiBandOffsets, origin);
        System.out.println("bandedRaster3: " + bandedRaster3);

        // Create raster from sample model and buffer
        BandedSampleModel multiModel = new BandedSampleModel(DataBuffer.TYPE_BYTE, width, height, width, multiBankIndices, multiBandOffsets);
        WritableRaster bandedRaster4 = Raster.createWritableRaster(multiModel, multiBuffer, origin);
        System.out.println("bandedRaster4: " + bandedRaster4);

        // Now let's create a suitable color model for these kinds of rasters,  with default sRGB color space
        ColorModel colorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), bands > 3, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);

        // Create images for all of the raster types
        BufferedImage image1 = new BufferedImage(colorModel, bandedRaster1, colorModel.isAlphaPremultiplied(), null);
        System.out.println("image1: " + image1);
        BufferedImage image2 = new BufferedImage(colorModel, bandedRaster2, colorModel.isAlphaPremultiplied(), null);
        System.out.println("image2: " + image2);
        BufferedImage image3 = new BufferedImage(colorModel, bandedRaster3, colorModel.isAlphaPremultiplied(), null);
        System.out.println("image3: " + image3);
        BufferedImage image4 = new BufferedImage(colorModel, bandedRaster4, colorModel.isAlphaPremultiplied(), null);
        System.out.println("image4: " + image4);

        // Fill with randomness to make it less dull
        Random random = new Random();
        random.nextBytes(singleData);
        for (byte[] bytes : multiData) {
            random.nextBytes(bytes);
        }

        // And finally display to prove it works just fine
        showIt(image1, "Image 1: Single bank, banded raster");
        showIt(image2, "Image 2: Single bank, banded, generic raster");
        showIt(image3, "Image 3: Multibank, banded raster");
        showIt(image4, "Image 4: Multibank, banded, generic raster");

        // Part II
        // Now, the single array image, could also be used to create somehting more standard (the images will *NOT* look the same, despite sharing data)

        // Create raster directly from buffer
        int[] interleavedOffsets = createIndices(bands, bands - 1, -1); // 2, 1, 0 (BufferedImage.TYPE_3BYTE_BGR has this order)
        WritableRaster interleavedRaster1 = Raster.createInterleavedRaster(singleBuffer, width, height, bands * width, bands, interleavedOffsets, origin);
        System.out.println("interleavedRaster1: " + interleavedRaster1);

        // Create raster from sample model and buffer
        PixelInterleavedSampleModel interleavedModel = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, width, height, bands, bands * width, interleavedOffsets);
        WritableRaster interleavedRaster2 = Raster.createWritableRaster(interleavedModel, singleBuffer, origin);
        System.out.println("interleavedRaster2: " + interleavedRaster2);

        // Create images for all of the raster types
        BufferedImage image5 = new BufferedImage(colorModel, interleavedRaster1, colorModel.isAlphaPremultiplied(), null);
        System.out.println("image5: " + image5);
        BufferedImage image6 = new BufferedImage(colorModel, interleavedRaster2, colorModel.isAlphaPremultiplied(), null);
        System.out.println("image6: " + image6);

        // Uncomment these lines, to better understand the difference between banded and interleaved :-)
//        Arrays.fill(singleData, bandSize, 2 * bandSize, (byte) 255);
//        Arrays.fill(multiData[1], (byte) 255);

        // And finally display to prove it works just fine
        showIt(image5, "Image 5: Single bank, interleaved raster");
        showIt(image6, "Image 6: Single bank, interleaved raster");
    }

    private static int[] createIndices(final int count, final int start, final int increment) {
        int[] indices = new int[count];

        for (int i = 0; i < count; i++) {
            indices[i] = start + i * increment;
        }

        return indices;
    }

    private static void showIt(final BufferedImage image, final String title) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame(title);
                frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {
                    @Override public void windowClosed(final WindowEvent e) {
                        if (Window.getWindows() == null || Window.getWindows().length == 0) {
                            System.exit(0);
                        }
                    }
                });
                frame.add(new JLabel(new ImageIcon(image)));
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
}

Here's what the test output looks like:
bandedRaster1: ByteBandedRaster: width = 300 height = 200 #bands 3 minX = 0 minY = 0
bandedRaster2: sun.awt.image.SunWritableRaster@450cceb3
bandedRaster3: ByteBandedRaster: width = 300 height = 200 #bands 3 minX = 0 minY = 0
bandedRaster4: sun.awt.image.SunWritableRaster@4bd66d2f
image1: BufferedImage@1e8ee5c0: type = 0 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@378dafec transparency = 1 has alpha = false isAlphaPre = false ByteBandedRaster: width = 300 height = 200 #bands 3 minX = 0 minY = 0
image2: BufferedImage@3718cb72: type = 0 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@378dafec transparency = 1 has alpha = false isAlphaPre = false sun.awt.image.SunWritableRaster@450cceb3
image3: BufferedImage@3cd4c5a0: type = 0 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@378dafec transparency = 1 has alpha = false isAlphaPre = false ByteBandedRaster: width = 300 height = 200 #bands 3 minX = 0 minY = 0
image4: BufferedImage@34faaa93: type = 0 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@378dafec transparency = 1 has alpha = false isAlphaPre = false sun.awt.image.SunWritableRaster@4bd66d2f
interleavedRaster1: ByteInterleavedRaster: width = 300 height = 200 #numDataElements 3 dataOff[0] = 2
interleavedRaster2: ByteInterleavedRaster: width = 300 height = 200 #numDataElements 3 dataOff[0] = 2
image5: BufferedImage@39a44220: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@378dafec transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 300 height = 200 #numDataElements 3 dataOff[0] = 2
image6: BufferedImage@4ef16070: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@378dafec transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 300 height = 200 #numDataElements 3 dataOff[0] = 2

PS: Bonus points to anyone who can explain why banded rasters 1 & 2 and 3 & 4 respectively are not equal or of the same type... I think they should be, as interleaved rasters 1 & 2 are equal.


text:
Q: Error de version con Xamarin.Android.Support Actualmente quiero usar XF.material y xamarin.google.maps y estoy usando Android 10.0 para compilar el proyecto pero al juntar esas variables me salio el siguiente error:
Gravedad    Código  Descripción Proyecto    Archivo Línea   Estado suprimido
Error   NU1107  Se detectó un conflicto de versiones para Xamarin.Android.Support.Compat. Para resolver este problema, instale o haga referencia a Xamarin.Android.Support.Compat 26.0.2 directamente en el proyecto PruebaGoogle.Android.
 PruebaGoogle.Android -> Xamarin.Forms.GoogleMaps 3.3.0 -> Xamarin.GooglePlayServices.Maps 60.1142.1 -> Xamarin.GooglePlayServices.Basement 60.1142.1 -> Xamarin.Android.Support.Compat (>= 26.0.2)
 PruebaGoogle.Android -> Xamarin.Forms.GoogleMaps 3.3.0 -> Xamarin.Android.Support.v7.AppCompat 25.1.0 -> Xamarin.Android.Support.Compat (= 25.1.0).    PruebaGoogle.Android    C:\ProyectosDesarrollo\PruebaGoogle\PruebaGoogle\PruebaGoogle.Android\PruebaGoogle.Android.csproj   1

Ademas de esos paquetes también estoy usando xam.plugin.geolocator, todos los paquetes en sus ultimas versiones.

A: Tenes que instalar los paquetes nuget que te marca desde el ultimo en la linea que te marca hasta el primero. lo mas facil es que uses la consola de paquetes.
Herramientas -> Administrador de paquetes nuget -> Consola del administrador de paquetes.
install-package Xamarin.Android.Support.Compat
install-package Xamarin.GooglePlayServices.Basement
install-package Xamarin.GooglePlayServices.Maps
install-package Xamarin.Forms.GoogleMaps


text:
Q: Redirect page and tacking on .html extension In my conf file,i want to rewrite all my URLs from a subdomain (blog.domain.com) to the root domain, removing the trailing slash (if available) and appending the ".html" extension.
blog.domain.com/my-first-link/  -->  www.domain.com/my-first-link.html

But i dont want the ".html" extension to be added for the root of the subdomain
blog.domain.com/                -->  www.domain.com

A: This should do it. Put this in the blog subdomain VirtualHost. If you don't have a blog VirtualHost it should work in the main host config as well.
RewriteEngine on
RewriteCond %{HTTP_HOST}  ^blog\.example\.com$
RewriteRule ^/$ http://www.example.com/ [R=301,L]
RewriteRule ^/(.*)/$ http://www.example.com/$1.html [R=301,L]


text:
Q: Validating member List variables for null values The structure that I have is something like below:
Class A{
    String str;
    int i;
    List<B> bs;
    C c;
    @NotNull
    List<D> ds;
}

Class B{
    @NotNull
    List<E> es;
}

Class C{
    List<String> s;
}

Class E{
    @NotNull
    List<String> s;
}

For the list variables that are annotated with @NotNull I need to throw validation error if any of them variables has one or more null objects. While for the other list variables I just need to remove the nulls;
What would be the best way to achieve this?

A: If you are using validation 2.0+ you can put annotation inside: List<@NotNull String> s;

A: You should define custom annotation for validating.
so define custom annotation like bellow.
@Target({ElementType.FIELD, ElementType.PARAMETER,ElementType.ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = ValidateListValidator.class)
@Documented
public @interface ValidateList {
}

and implement ValidateListValidator like this:
public class ValidateListValidator implements ConstraintValidator<ValidateList, List<Object>> {

private ValidateList validateList;
@Override
public void initialize(ValidateList validateList) {
    this.validateList = validateList;
}

@Override
public boolean isValid( List<Object> list, ConstraintValidatorContext constraintValidatorContext) {
    return list.stream().noneMatch(Objects::isNull);
  }

 }

and for test it
@Test
public void test() {
    boolean valid = validator.isValid(Arrays.asList("test","this",null),context);
    assertThat(valid, is(false));
}

A: This is the final code that I wrote, just a few tweaks to the code that Hadi posted. I hope it helps:
Annotation:
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ListValidator.class)
@Documented
public @interface ValidList {
  String message() default "Null values are not allowed in array fields.";

  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};
}

Validator Class:
import java.util.List;
import java.util.Objects;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ListValidator implements ConstraintValidator<ValidList, List<? extends Object>> {

  @Override
  public boolean isValid(List<? extends Object> list, ConstraintValidatorContext context) {
    return list.stream().noneMatch(Objects::isNull);
  }

  @Override
  public void initialize(ValidList constraintAnnotation) {}
}


text:
Q: Aggregating finer raster data to 25-km grid using a point shapefile I have a series of lat long from a point shapefile which is 25-km grid
lon <- c(-53.615449969, -53.365449969, -53.115449969, -53.365449969,
         -53.115449969, -52.865449969, -53.365449969, -53.115449969, -52.865449969,
         -52.615449969, -53.365449969, -53.115449969, -52.865449969, -52.615449969,
         -52.365449969, -53.365449969, -53.115449969, -52.865449969, -52.615449969,
         -52.365449969, -53.615449969, -53.365449969, -53.115449969, -52.865449969,
         -52.615449969, -52.365449969, -52.115449969, -53.865449969, -53.615449969,
         -53.365449969, -53.115449969, -52.865449969, -52.615449969, -52.365449969,
         -52.115449969, -51.865449969, -54.365449969, -54.115449969, -53.865449969,
         -53.615449969, -53.365449969, -53.115449969, -52.865449969, -52.615449969,
         -52.365449969, -52.115449969, -51.865449969, -51.615449969, -54.615449969,
         -54.365449969, -54.115449969, -53.865449969, -53.615449969, -53.365449969,
         -53.115449969, -52.865449969, -52.615449969, -52.365449969, -52.115449969,
         -51.615449969)

lat <- c(-33.627081271, -33.627081271, -33.627081271, -33.377081271,
         -33.377081271, -33.377081271, -33.127081271, -33.127081271, -33.127081271,
         -33.127081271, -32.877081271, -32.877081271, -32.877081271, -32.877081271,
         -32.877081271, -32.627081271, -32.627081271, -32.627081271, -32.627081271,
         -32.627081271, -32.377081271, -32.377081271, -32.377081271, -32.377081271,
         -32.377081271, -32.377081271, -32.377081271, -32.127081271, -32.127081271,
         -32.127081271, -32.127081271, -32.127081271, -32.127081271, -32.127081271,
         -32.127081271, -32.127081271, -31.877081271, -31.877081271, -31.877081271,
         -31.877081271, -31.877081271, -31.877081271, -31.877081271, -31.877081271,
         -31.877081271, -31.877081271, -31.877081271, -31.877081271, -31.627081271,
         -31.627081271, -31.627081271, -31.627081271, -31.627081271, -31.627081271,
         -31.627081271, -31.627081271, -31.627081271, -31.627081271, -31.627081271,
        -31.627081271)

  df <- as.data.frame(cbind(lon, lat))
  df$ID <- 1:nrow(df)
  coordinates(df) <- c(1,2)
  plot(df, pch = 0)

Why are the squares not touching each other? I thought if this is a 25-km grid, all the squares should be sharing their respective boundaries.

A: What you've created is a SpatialPointsDataFrame - when you plot it, you get markers centred at the points. Using pch=0 uses a square marker, but it has no idea of the data being a regular grid. You can plot the marker with different sizes - try:
plot(df, pch = 0, cex=6)
plot(df, pch = 0, cex=0.5)

or with a different marker:
plot(df, pch="Z")


text:
Q: Javascript Matrix Calculator with HTML form I have a website that teaches students finite math http://finitehelp.com.
On the site I have a calculator that does combinations and permutations and now I am trying to include a matrix calculator that will add, subtract, multiply, and inverse matrices.
I am using Javascript and the sylvester library http://sylvester.jcoglan.com/ to do the calculations. I was able to successfully create a program that would take values entered into a form by a user and do the calculations but this only works for a matrix of a specific size (4x4).
What I cannot figure it out is how to only take values from a form which are not null and create a matrix out of them and then output those values into the appropriate fields in the result form.
Some Sylvester methods I am using
// create matrix from embedded array and assign to var A
var A = $M([
  [8,3,9],
  [2,0,7],
  [1,9,3]
]);

// create matrix from embedded array and assign to var B
var B = $M([
  [4,1,2],
  [1,5,3],
  [1,7,2]
]);

 // Multiply AB
 A.x(B)

 // assign product of A.x(B) to var res
 var res = A.x(B)

 // return the 1,1 element of res
 res.e(1,1)

In my form the biggest matrix you can put in is 6x6 because they will never need to calculate matrices larger than this.
What I need the program to do is detect how large the matrices are, create sylvester matrices out of them, and assign them to variables. Once they are variables I can use sylvester to do the operations but I also will need to know how to output the results into a form.
Here is what I have so far
Javascript:
window.onload = function()
{
    document.getElementById('mbutton').onclick = doCalc;
    document.getElementById('subtbutton').onclick = doCalc;
    document.getElementById('addbutton').onclick = doCalc;
}
function doCalc() {
    // assign the inputted values to variables
    var Aval1 = document.matrixCalc.AR1C1.value,
        Aval2 = document.matrixCalc.AR1C2.value,
        Aval3 = document.matrixCalc.AR2C1.value,
        Aval4 = document.matrixCalc.AR2C2.value,
        Bval1 = document.matrixCalc.BR1C1.value,
        Bval2 = document.matrixCalc.BR1C2.value,
        Bval3 = document.matrixCalc.BR2C1.value,
        Bval4 = document.matrixCalc.BR2C2.value;

    // make matrices out of the inputted values and assign to variables
    var A = $M([
        [Aval1,Aval2],
        [Aval3,Aval4]
        ]);
    var B = $M([
        [Bval1,Bval2],
        [Bval3,Bval4]
        ]);
    // if user clicks multiply button make the values of
    // the answer form show the appropriate values
    if (this.value == "x") {
        var res = A.x(B);
        document.matrixCalc.PR1C1.value = res.e(1,1);
        document.matrixCalc.PR1C2.value = res.e(1,2);
        document.matrixCalc.PR2C1.value = res.e(2,1);
        document.matrixCalc.PR2C2.value = res.e(2,2);
    } else if (this.value == "-") {
        var res = A.subtract(B);
        document.matrixCalc.PR1C1.value = res.e(1,1);
        document.matrixCalc.PR1C2.value = res.e(1,2);
        document.matrixCalc.PR2C1.value = res.e(2,1);
        document.matrixCalc.PR2C2.value = res.e(2,2);
    } else if (this.value == "+") {
        document.matrixCalc.PR1C1.value = parseFloat(Aval1) + parseFloat(Bval1);
        document.matrixCalc.PR1C2.value = parseFloat(Aval2) + parseFloat(Bval2);
        document.matrixCalc.PR2C1.value = parseFloat(Aval3) + parseFloat(Bval3);
        document.matrixCalc.PR2C2.value = parseFloat(Aval4) + parseFloat(Bval4);
    }
}

HTML form:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<form name="matrixCalc" action="">

Matrix A

    <input type="text" name="AR1C1" size="4" />
    <input type="text" name="AR1C2" size="4" />
    <input type="text" name="AR1C3" size="4" />
    <input type="text" name="AR1C4" size="4" />
    <input type="text" name="AR1C5" size="4" />
    <input type="text" name="AR1C6" size="4" />

    <input type="text" name="AR2C1" size="4" />
    <input type="text" name="AR2C2" size="4" />
    <input type="text" name="AR2C3" size="4" />
    <input type="text" name="AR2C4" size="4" />
    <input type="text" name="AR2C5" size="4" />
    <input type="text" name="AR2C6" size="4" />

    <input type="text" name="AR3C1" size="4" />
    <input type="text" name="AR3C2" size="4" />
    <input type="text" name="AR3C3" size="4" />
    <input type="text" name="AR3C4" size="4" />
    <input type="text" name="AR3C5" size="4" />
    <input type="text" name="AR3C6" size="4" />

    <input type="text" name="AR4C1" size="4" />
    <input type="text" name="AR4C2" size="4" />
    <input type="text" name="AR4C3" size="4" />
    <input type="text" name="AR4C4" size="4" />
    <input type="text" name="AR4C5" size="4" />
    <input type="text" name="AR4C6" size="4" />

    <input type="text" name="AR5C1" size="4" />
    <input type="text" name="AR5C2" size="4" />
    <input type="text" name="AR5C3" size="4" />
    <input type="text" name="AR5C4" size="4" />
    <input type="text" name="AR5C5" size="4" />
    <input type="text" name="AR5C6" size="4" />

    <input type="text" name="AR6C1" size="4" />
    <input type="text" name="AR6C2" size="4" />
    <input type="text" name="AR6C3" size="4" />
    <input type="text" name="AR6C4" size="4" />
    <input type="text" name="AR6C5" size="4" />
    <input type="text" name="AR6C6" size="4" />

Matrix B

    <input type="text" name="BR1C1" size="4" />
    <input type="text" name="BR1C2" size="4" />
    <input type="text" name="BR1C3" size="4" />
    <input type="text" name="BR1C4" size="4" />
    <input type="text" name="BR1C5" size="4" />
    <input type="text" name="BR1C6" size="4" />

    <input type="text" name="BR2C1" size="4" />
    <input type="text" name="BR2C2" size="4" />
    <input type="text" name="BR2C3" size="4" />
    <input type="text" name="BR2C4" size="4" />
    <input type="text" name="BR2C5" size="4" />
    <input type="text" name="BR2C6" size="4" />

    <input type="text" name="BR3C1" size="4" />
    <input type="text" name="BR3C2" size="4" />
    <input type="text" name="BR3C3" size="4" />
    <input type="text" name="BR3C4" size="4" />
    <input type="text" name="BR3C5" size="4" />
    <input type="text" name="BR3C6" size="4" />

    <input type="text" name="BR4C1" size="4" />
    <input type="text" name="BR4C2" size="4" />
    <input type="text" name="BR4C3" size="4" />
    <input type="text" name="BR4C4" size="4" />
    <input type="text" name="BR4C5" size="4" />
    <input type="text" name="BR4C6" size="4" />

    <input type="text" name="BR5C1" size="4" />
    <input type="text" name="BR5C2" size="4" />
    <input type="text" name="BR5C3" size="4" />
    <input type="text" name="BR5C4" size="4" />
    <input type="text" name="BR5C5" size="4" />
    <input type="text" name="BR5C6" size="4" />

    <input type="text" name="BR6C1" size="4" />
    <input type="text" name="BR6C2" size="4" />
    <input type="text" name="BR6C3" size="4" />
    <input type="text" name="BR6C4" size="4" />
    <input type="text" name="BR6C5" size="4" />
    <input type="text" name="BR6C6" size="4" />

    <input type="button" id="mbutton" value="x" />
    <input type="button" id="addbutton" value="+" />
    <input type="button" id="subtbutton" value="-" />

Answer

    <input type="text" name="PR1C1" size="4" />
    <input type="text" name="PR1C2" size="4" />
    <input type="text" name="PR1C3" size="4" />
    <input type="text" name="PR1C4" size="4" />
    <input type="text" name="PR1C5" size="4" />
    <input type="text" name="PR1C6" size="4" />

    <input type="text" name="PR2C1" size="4" />
    <input type="text" name="PR2C2" size="4" />
    <input type="text" name="PR2C3" size="4" />
    <input type="text" name="PR2C4" size="4" />
    <input type="text" name="PR2C5" size="4" />
    <input type="text" name="PR2C6" size="4" />

    <input type="text" name="PR3C1" size="4" />
    <input type="text" name="PR3C2" size="4" />
    <input type="text" name="PR3C3" size="4" />
    <input type="text" name="PR3C4" size="4" />
    <input type="text" name="PR3C5" size="4" />
    <input type="text" name="PR3C6" size="4" />

    <input type="text" name="PR4C1" size="4" />
    <input type="text" name="PR4C2" size="4" />
    <input type="text" name="PR4C3" size="4" />
    <input type="text" name="PR4C4" size="4" />
    <input type="text" name="PR4C5" size="4" />
    <input type="text" name="PR4C6" size="4" />

    <input type="text" name="PR5C1" size="4" />
    <input type="text" name="PR5C2" size="4" />
    <input type="text" name="PR5C3" size="4" />
    <input type="text" name="PR5C4" size="4" />
    <input type="text" name="PR5C5" size="4" />
    <input type="text" name="PR5C6" size="4" />

    <input type="text" name="PR6C1" size="4" />
    <input type="text" name="PR6C2" size="4" />
    <input type="text" name="PR6C3" size="4" />
    <input type="text" name="PR6C4" size="4" />
    <input type="text" name="PR6C5" size="4" />
    <input type="text" name="PR6C6" size="4" />

Any help would be appreciated. When answering please keep in mind that this is only the second time I've tried to write a program so that little bit extra in the explanation could help a great deal. Thank you.

A: I think you will find it better to use a textarea and let users type in matrices in a much more natural format. It will require parsing the content, but that's not hard. That way users can create any size matrix. I can post a generic "parse textarea content to make an array" function a little later.
Also, the maths isn't that hard. I did it some time ago (products, addition, determinants) but can't find where I put it. Determinants were the most difficult, if I remember correctly it was a simple matter of splitting larger matrices into 2x2 matrices and adding and subtracting their determinants (everything I needed was on the Wolfram web site).


text:
Q: Catch REFERENCE constraint exception from SQL in C# What will be proper way to catch exception which throw SQL server when I deleting data with Reference constraint from C# code.
I want to show my users message like:
"I can't delete the data because is used"
, rather than of showing message like this:
The DELETE statement conflicted with the REFERENCE constraint ... The conflict ccurred*in database "rampa", table "dbo.doc", column 'kartica_id'.

A: Use this:
try
{
   //Execute delete statement
}
catch (SqlException sqlEx)
{
   //Handle exception
}
finally
{
   //Close connection
}

All sql errors are thrown as SqlException and there are no specific errors. To find out what was error exactly, there is property SqlException.Number which is the same as SQL Error Code. You can find the list of codes here.

A: You can access the ConstraintException and map its fields however you want to your own preferred error output.
using System.Data;

try
{
  // code that violates constraint
}
catch (ConstraintException exc)
{
  // build output message you wish using exc.Message and other fields,
  // return cleanly or rethrow as your own exception
}


text:
Q: If $\cos\theta$ is rational, then is $\cos k\theta$ also rational? If $\cos\theta$ is rational, then is $\cos k\theta$ also rational, where $k$ is a positive integer? I tried a few simple cases, and they worked. Is it true? And if it is then how do I go about rigorously proving this?
I've tried using the identity of $\cos(A+B)$ with induction, but am not able to prove it.
Thanks.

A: We have
$$\cos k\theta=T_k(\cos\theta)$$
where $T_k$ is the $k$th Chebyshev polynomial of the first kind. Since all Chebyshev polynomials have integral coefficients and $\cos\theta$ is rational, $\cos k\theta$ must also be rational.

For a lower-level proof, de Moivre's formula gives $\cos k\theta$ as the real part of $(\cos\theta+i\sin\theta)^k$, expanding to
$$\cos k\theta=\sum_{l=0}^{\lfloor k/2\rfloor}\binom k{2l}\sin^{2l}\theta\cos^{k-2l}\theta$$
Since $\sin^2x=1-\cos^2x$:
$$\cos k\theta=\sum_{l=0}^{\lfloor k/2\rfloor}\binom k{2l}(1-\cos^2\theta)^l\cos^{k-2l}\theta$$
Since binomial coefficients are integers, the RHS is an integer polynomial in $\cos\theta$, so $\cos k\theta$ is rational. In fact, this polynomial is one way to define the $T_k$.


text:
Q: Special relativity for accelerated trajectories 'There is no truth to the rumor that SR is unable to deal with accelerated trajectories and general relativity must be invoked.' Can some one explain it.
I used to think SR is for flat spacetime and GR is for curved spacetime.

A: Yes, special relativity deals with the flat spacetime $(\Bbb{R}^4,\eta)$, and GR deals generically with curved spacetimes $(M,g)$. So, the distinction between SR and GR comes in the form of curvature of (the Levi-Civita connection of) the metric, and it is the curvature which models gravity, i.e SR deals with zero (or 'weak') gravity while GR deals with non-zero gravity (even on the astronomical scale).
Now, we can talk about acceleration just as well in either case. The concept of acceleration of a curve $\gamma$ can be defined in every Lorentzian manifold- flat or not- via the simple expression $\nabla_{\dot{\gamma}}\dot{\gamma}$, where $\nabla$ is the Levi-Civita connection of the metric.  Let me emphasize the following point though: the notion of acceleration depends on the metric tensor (because the metric tensor determines the Levi-Civita connection $\nabla$). So you can consider different spacetimes $(M,g_1),(M,g_2)$ with the same underlying manifold but different metric tensor. If you consider the same curve $\gamma:\Bbb{R}\to M$, then you may find that $\gamma$ has zero acceleration with respect to $g_1$, but non-zero acceleration with respect to $g_2$.
If a curve $\gamma$ satisfies $\nabla_{\dot{\gamma}}\dot{\gamma}=0$, then we say the curve is not accelerating; the terminology in differential geometry is that $\gamma$ is a geodesic. In SR, the spacetime and underlying geometry is so simple that all the mathematical machinery reduces to the naive things we expect: geodesics in $(\Bbb{R}^4,\eta)$ are precisely the straight lines in $\Bbb{R}^4$, and any curve which is not a straight line thus has non-zero acceleration.
So, to reiterate, there is no contradiction between the statements "SR deals with flat spacetimes $(\Bbb{R}^4,\eta)$" and "we can talk about accelerating observers in SR". Things may sound confusing if you start excessively working exclusively with coordinates in the beginning because the introduction of coordinates obscures the geometry (and hence the physics).

A: There is no real acceleration in a flat spacetime as a whole; Since in spacetime our velocity is always equal to the speed of light, we can't speed up or slow down inside spacetime as a whole...
Sure we can go faster in space, but we will also go slower in time... Meaning that we can accelerate in space but by doing so, we will also desselerate in time... At the end, our net speed will continue to be equal to the speed of light no matter what we do!
That is called a hyperbolic rotation, and its the only way to move in spacetime.


text:
Q: what is the complexity of function that have loop inside recursion function im trying to analysis the complexity of this code .
i predicated that its o(n^2)
because for loop take a o(n) inside a recursion function thats take o(n)
o(n) * o(n) = o(n^2)
however im not sure .
public class main
{

    static Set<String> setString = new HashSet<>();

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        main m = new main();
        m.permute("sanad", 0);
        for(String s : setString)
        {
            System.out.println(s);
        }

    }

    public void permute(String str , int i )
    {
        if (i>=str.length())
        {
            return;
        }

        for(int j = 0 ; j < str.length();j++)
        {
            StringBuilder b = new StringBuilder(str. replaceFirst(String.valueOf(str.charAt(i)), ""));
            b.insert(j,str.charAt(i));
            setString.add(b.toString());
        }

        permute(str, ++i);
    }

}

A: You are correct in that the total complexity is the product of the nested complexities and that the permute function is called n times, where n is the length of the string, and the loop is called n times as well, leading to n^2 calls of the loop . However you also have to look at the complexity of the code inside the loop, especially replaceFirst and insert, decide, if their runtime depends on the length of the string, and multiply with that as well. As I suspect this is a homework question I leave this to you.


text:
Q: Excel formula to group values which meets specified creteria See example below:

I'm looking for a single cell formula, which I can put in cell D2. I want this function to extract each value from Column B, where corresponding value in Column A equals "YES".
Is anything like this possible in cell formula, without using VBA?

A: You can use array formulas, which essentially compute calculations in an array and can be aggregated. As JvdV mentioned, you can use TEXTJOIN.
=TEXTJOIN(";",TRUE,IF(A1:A6="YES",B1:B6,""))

To use an array formula, if you haven't before, you need to finish your formula by entering SHIFT+ENTER, otherwise it will be interpreted as a regular, non-array, formula.

A: If you do not have TEXTJOIN() function then use below UDF.
Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
End Function

Use as array formula in your case
=TEXTJOIN(";",TRUE,IF(A1:A6="YES",B1:B6,""))

Press CTRL+SHIFT+ENTER to evaluate the formula as it is an array formula.

The credit goes to Scott Craner from this post. TextJoin UDF For Excel 2013


text:
Q: Installing ArcView 3 on 64-bit Windows? How do I install ArcView 3 on 64bit Windows?
There are numerous threads on the Esri forums for how to accomplish this, but the solutions are scattered, inconsistent and disjointed.
This is a request to post integrated and "cleaned-up" solutions, don't just copy and paste. Please indicate if the method is specific to x64 XP, Vista, or 7 (and post seperately, e.g. win7 method in one answer, vista in another).

A: Install Arcview on XP, using the defaults.
Copy these folders to the same location on Win7.
C:\esri
C:\Program Files\Common Files\ESRI

For 64bit Windows use target C:\Program Files (x86)\Common Files\ESRI instead.

A: For Win7/64: Copy all the files from a working installation.  Put them into identically named drives and folders on the destination machine.  Run it!  This really does work: I have been using AV 3.3 in this mode for the last eight months.  This is the fourth or fifth migration of this sort since the last official install I did about a decade ago.  Also working is Spatial Analyst 1.1, which I have not installed from CD in about 14 years.
I also tried the Windows VM solution (which emulates Win XP/32).  It's awful: there's some kind of incompatibility that causes AV to hang after a fraction of a second and wait for user interaction.  If you keep waving your mouse over the window, it will keep chugging away at a redraw or table processing, but it's still incredibly slow.  After hunting the Web for a few weeks to locate a solution, to no avail, I gave up on this kluge.

If you have problems with reports of missing DLL files after the migration, please see this answer by klewis for a potentially simple fix.  You might also need to migrate special files installed by your ArcView extensions if they placed them in idiosyncratic locations.

A: After installing via the other answers, there are couple of things to make things a little friendlier (on Win7):
Register the .apr filename extension so you can just 2x-click on SomeProject.apr and thereby bypass the painful AV3 file chooser. Run these command from an administrative command prompt (edit to suit, see ss64 for usage):
assoc .apr=ArcView3.Project
ftype ArcView3.Project=C:\ESRI\ARCVIEW\BIN32\arcview.exe "%1"

Install Windows Help Program (WinHlp32.exe) from Windows Update KB917607, assuming you want to read the AV3 help docs that is.

A: fyi, Thought I'd post my 'final conclusion' after a few days of searching for the right answer and coming across numerous, cumbersome processes to get AV3x on to 64 bit Windows 7. I stumbled upon a pretty obscure but seemingly straight forward answer, somewhere... You can simply download a 32 bit 'installshield engine' - setup32.exe - and use that to install the AV3x files from original installation media - instead of the 16 bit 'setup.exe' that normally comes with ArcView 3x... Put setup32.exe in the same folder as the ArcView 3x installation stuff, double click, and it installs normally. You might have to run that program in Windows XP compatability mode...
I had used a version of AV3x that I copied from an XP installation, but ran into a few problems here and there. For example, the projection utility wouldn't work. Trying to fix that I got fed-up with all the 'change the registry' stuff, copy this, copy that - so I tried this setup32.exe way. Seems to work so far, projection utility works, though there may be some issues with that that I haven't figured out yet. Everything else I've tried works, though granted, I haven't done a whole lot yet...
edit: Here's a link to the page I found that talks about using Installshield 32 bit vs. 16 bit, which includes a link to "setup32.exe", scroll down to "Installshield3 shortcut" at that page:
http://www.reactos.org/forum/viewtopic.php?f=22&t=10988

A: Install ESRI_Arcview.zip in C: Drive (this is just a zip of the C:\Esri folder from a previous install)
Install Common_files_ESRI in C:\Program Files (x86)\Common Files (again a copy of the previous files)
Install Fonts.zip in Fonts (esri_1.ttf to esri_9.ttf)
Create a HOME environment variable to point to a home folder
Install avenv.ave in the HOME folder (optional startup file that can set local environment etc. In my case it adds a third party extension set of tools)
Make up a shortcut to C:/ESRI/AV_30/bin/arcview.exe
Set opening *.apr files to use arcview.exe
This works for me in Windows 10 without any virtual machines or other hacks.
This assumes a valid licence key.


text:
Q: How to use use ndb library schemeless using datastore client library.
Can be used regardless of the state of the datastore property.
datastore_client.put({
  "foo":"foo",
  "bar":"bar",
  "xxx":"xxx", # any property can put
  ...
})

But, using ndb.
Only predefined properties can be used.
Class Test(ndb.Model):
  foo = StringProperty()
...
Test(
  foo="foo",
  bar="bar" # error
).put()

If I want to put()/get() schemeless.
I cannot use ndb?

A: Look for ndb.Expando .This is what you want


text:
Q: Authenticate requests between WPF and PHP using oAuth2? I've searched for a while now but couldn't find anything related to my thoughts. I want to build an application with WPF which is getting all user related information sending requests to a PHP script. For every request I use SSL.
When the user registers he only submit his username, password and email address. The password is always stored as a hash in the application using sha256 and this hash is stored as another hash using password_hash in PHP.
After the login the application is sending a request based on the users action. To verify each request I came across oAuth2. Is oAuth2 the "best practice" to verify requests or is there another way to do it? It is necessary to verfiy each request after the login.

A: OAuth is probably going to be your best bet. Being able to validate requests and revoke tokens is key when working within applications now a days.  Many of the top websites, Facebook, Twitter, Instagram, etc. all use OAuth due to it's robust authentication and flexibility.
For my company, we have custom built API's and utilize OAuth for all of them.  Even though they are private API's, OAuth gives us the ability to push for public use later if we so pleased.
Not sure exactly what your project is or how it functions, and quite frankly, I don't need to.  In my opinion, you cannot go wrong utilizing OAuth.

A: There are two common ways of securing an API request:

*

*Basic authentication. A header of the form
Authorization: Basic base64(username:password)

is sent along with every request. This is simple to implement, but also simple to attack; you absolutely must be sending the requests over HTTPS (since no encryption is being used).

*Some form of OAuth. You might use the password grant type for a scenario like yours: you send the username and password to the OAuth server and request an access token that can be used on each request. This is more secure, and more complicated, because you have to implement a token server.
What you choose depends on a lot of factors, like whether your service is internal or external, how much complexity you want to build into the project, and who the target users are.
Further reading:

*

*API Keys vs HTTP Authentication vs OAuth in a RESTful API

*HTTP Authentication

*What the Heck is OAuth?

*How to Secure an API (not WPF-related, but good video)

Full disclosure: I work at a company that builds an API for this.


text:
Q: How do i dynamically export variable angular I am trying to export x into the HTML in a way where I can increase it by one every half second. But it looks like it's only exporting on build. I already tried injection and ngOnChanges, ngDoCheck but it's very possible that I did something wrong I am only programming with angular for about a week.
landing.component.ts
    import { Component, OnInit} from '@angular/core';

    var printTime = window.setInterval(increaseX, 500);
    var x = 0;

    function increaseX() {
      x++;
    }

    @Component({
      selector: 'app-landing',
      templateUrl: './landing.component.html',
      styleUrls: ['./landing.component.css']
    })

    export class LandingComponent{
      x = x;
    }

landing.component.html

I Love
<{{x}}/>

Rusulting Website

A: Try to use BehaviorSubject
 @Component({
  selector: 'app-root',
  template: '
{{this.$subject|async}}
'
 })
 export class AppComponent implements OnInit {
   $subject: BehaviorSubject<number> = new BehaviorSubject<number>(1);

   ngOnInit(): void {
    window.setInterval(() => this.$subject.next(this.$subject.value + 1), 500);
   }
 }

A: The reason it's not working, is because x is a primitive value. So when you do x = x, you are only assigning it once. When you change it outside of the class, this will not update the primitive field created on the class. It is anyways not recommendable to do things outside of classes like you have there.
The solution depends all on what you want. Personally I think you are better of using a service here. This will decouple any logic from the component and delegate it to the service:
@Injectable({
  providedIn: 'root'
})
export class XService {
  x = 0;

  constructor() {
    window.setInterval(() => increaseX(), 500);
  }

  private increaseX(): void {
    this.x++;
  }
}

You can then access this value in your component:
export class LandingComponent{
  constructor(readonly xs: XService) {}
}

and show it in your template:

I Love
<{{xs.x}}/>

But, this will not work if you use OnPush change detection strategy, which is a recommended thing to use. You can even make it all cool and use the Observable pattern with the async pipe for this, which will look like this:
@Injectable({
  providedIn: 'root'
})
export class XService {
  readonly x$ = interval(500);
}

and your template

I Love
<{{xs.x$ | async}}/>

This will survive the OnPush change detection.
I've created a stackblitz for this solution

However, if you are just looking for a quick fix, you only have to change one thing really with your original code, and that is to make the x a getter on your component:
@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})

export class LandingComponent{
  get x() { return x; }
}

This will then always get the updated value of x. Again though, this is not OnPush 'worthy'

A: This also works.
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})

export class LandingComponent implements OnInit  {
  x: number = 0;

  constructor() {}

  ngOnInit() {
    const self = this;
    setInterval(() => ++self.x, 500);
  }
}


text:
Q: Evalute an Xpath attribute using XPathFactory I'm trying to do something quite simple I think, simply assert that an attribute of an Xpath node is a specific value. The node has no value, onlya an attribute value as follows:-
<ControlResponse Success="true"/> (will return "true" or "false")
<?xml version="1.0" encoding="UTF-8"?><tag0:AAA_ControlRS xmlns:tag0="http://www.xmltravel.com/fab/2002/09" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Target="test"     Version="2002A" xsi:type="AAA_ControlRS">
<tag0:TestInfo TestId="THFTEST"/>
<tag0:SessionInfo CreateNewSession="true"/>
<AAASessionId="8IzujBAVOPVQrO1ySpNBoJ9x"/>
<tag0:ControlResponse Success="true"/>
</tag0:AAA_ControlRS>

and here is my code:
//REQUEST
    String controlRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n...
//bunch of xml here";

   //RESPONSE
    String myControlResponse = given().
            when().
            request().
            contentType("text/xml").
            body(myControlRequest).
            when().post().andReturn().asString();

    //Parse response and get relevant node via Xpath
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder;
    Document doc;

    try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse(new InputSource((new StringReader(myControlResponse))));

        //Xpath Factory Object
        XPathFactory xPathFactory = XPathFactory.newInstance();

        //Xpath Object
        XPath xpath = xPathFactory.newXPath();

        String controlResponse = getNodeValue(doc, xpath);

        assertEquals("true", controlResponse);

    } catch (ParserConfigurationException | org.xml.sax.SAXException | IOException e) {
        e.printStackTrace();
    }
}

private static String getNodeValue(Document doc, XPath xpath) {
    String controlResponse = null;
    try {
        XPathExpression expr =
                xpath.compile("//ControlResponse/@Success");
        controlResponse = (String) expr.evaluate(doc, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return controlResponse;
}

The xpath evaluates to null when I expect the String "true". I want to achieve getting the attribute value and asserting if it contains string "true" or "false"
Is there an easier way of achieving what I'm trying to do?

A: To get the attribute value, use //ControlResponse/@Success as the XPath expression.
If namespace issues get in your way, use //*[local-name()="ControlResponse"]/@Success for a quick check, if the problem is namespace related.
Example using an unrelated sample document:
> cat ~/test.xml
<root><foo bar="true"/></root>
> xmllint --xpath '//foo/@bar' ~/test.xml
 bar="true"

If this doesn't work as expected in your case, please show enough of the XML document that the problem is reproducible.


text:
Q: Change string mm/dd/yyyy format date to datetime dd/mm/yyyy format date I have used string in accepting the parameter in the controller for dates.
public ActionResult Export(string fromDate, string toDate)
{
    if (!string.IsNullOrEmpty(fromDates))
         DateTime dDate = DateTime.Parse(fromDates);
    if (!string.IsNullOrEmpty(toDates))
         DateTime dDate = DateTime.Parse(toDates);
}

Convert from "03/30/2018" to 30/03/2018 12:00:00 AM
Please help me. Thanks.

A: Use DateTime.ParseExact with CultureInfo.InvariantCulture:
DateTime fromDateDt = DateTime.ParseExact( fromDate, "MM/dd/yyyy", CultureInfo.InvariantCulture );
DateTime toDateDt   = DateTime.ParseExact( toDate  , "MM/dd/yyyy", CultureInfo.InvariantCulture );

A: Use DateTme.ParseExact you can try with the below code :
DateTime ConvertedVal = DateTime.ParseExact("03/30/2018", "MM/dd/yyyy", null);

Sample Demo
https://dotnetfiddle.net/fuc3PN


text:
Q: How to get duplicate results in two or more joined tables? I have two tables:

*

*orders (id);

*order_items(id, order_id, item_id, quantity)

Let's say I have already selected an order X with 3 different items (A - 1 unit, B - 2 units and C - 1 unit).
I need to get all the orders that have same items and exactly the same quantity of items (in this case:  A - 1 unit, B - 2 units and C - 1 unit and no more or no less :)), excluding an order X.
i made a dump of test tables, so, I hope, for You would be easier to understand, what I'd like to get:) http://nopaste.info/44eb93ae3d.html
lets assume order X = 1, so desired output would be only the order 2, because order 3 has only one item and order 4 has same items as #1, but it has also one item extra, so it is not good :)

A: Count the same occurence of each orders in the order_items table, and then compare to the number of item of the searched order:
SELECT i2.order_id
FROM order_items i1
    RIGHT OUTER JOIN order_items i2
        ON i2.item_id = i1.item_id
        AND i2.quantity = i1.quantity
        AND i1.order_id = 1
WHERE i2.order_id  != 1
GROUP BY i2.order_id
HAVING COUNT(i1.order_id) = COUNT(*)
   AND COUNT(i1.order_id) = (SELECT COUNT(*) FROM order_items WHERE order_id = 1)

Note that this query assume that (order_id, item_id) is a Key of the order_items table.
I have made a sample test here.

A: select *
from orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN (select *
      from orders o2
      JOIN order_items oi2 ON o2.id = oi2.order_id
      WHERE o2.id = @X) sub
ON oi.quantity = sub.quantity
AND oi.item_id = sub.item_id
WHERE o.id <> @X

EDIT:
select *
from orders o
JOIN order_items oi ON o.id = oi.order_id
JOIN (select *
      from orders o2
      JOIN order_items oi2 ON o2.id = oi2.order_id
      WHERE o2.id = @X) sub
ON oi.quantity = sub.quantity
AND oi.item_id = sub.item_id
AND NOT EXISTS (select 1
                from order_items
                where order_id = o.id
                and concat(item_id,quantity) not in (select concat(itemid,quantity)
                                                     from order_items
                                                     where order_id = o.id))
WHERE o.id <> @X


text:
Q: Where methods live? Stack or in Heap? I know that local variables and paramters of methods live in stack, but I not able to figure out where does actually methods live in case of Java?
If I declare any Thread object like:
Thread t=new Thread();
t.start();

So it means I've created a separate calling of methods apart from main method. What does it mean? Does it mean calling of separate sequence of methods over Stack memory? Am I right?

A: Each thread is allocated its own stack.
This article has a good introduction to the memory separation within a Java process.

Inside the Java virtual machine, each
  thread is awarded a Java stack, which
  contains data no other thread can
  access, including the local variables,
  parameters, and return values of each
  method the thread has invoked. The
  data on the stack is limited to
  primitive types and object references.
  In the JVM, it is not possible to
  place the image of an actual object on
  the stack. All objects reside on the
  heap.

I've seen many scenarios where clients have implemented hugely threaded servers on the basis that each thread does very little, and they run into problems with memory. That's because each thread is allocated its own stack, and this (obviously) adds up. I think the default value is 512k per thread, but I've not found a canonical source for that.

A: If I remember correctly, the method code itself will live in the code portion of memory, while the variables declared internally will live in the stack, and the objects will be created on the heap.  In Java, the variable pointers and primitives live on the stack, while any created objects live in the heap.
For a (poor) ASCII representation:
-------
|STACK|
-------
|FREE |
-------
|HEAP |
-------
|CODE |
-------

Where the STACK represents the stack, FREE represents free memory, HEAP represents the heap, and CODE represents the code space.
This is what my memory says - some of the details might be wrong.

A: The stack is comprised of method invocations. What java pushes onto the stack is a method invocation record, which encapsulates all the variables (both parameters and locally instantiated variables) for that method. When you start a Java application, the main method (which automatically includes the args parameter) is the only thing on the stack:
main(args)

When say you create a Foo object and call foo.method(), the stack now looks like:
method()
main(args)

As methods get called, they are pushed onto the stack, and as they return, they are removed or "popped" from the stack. As variables are declared and used the stack entry, which corresponds to the current method (at the top of the stack), grows to include the size of the variable.
For your example with threads, each thread will have its own stack which exists independent of each other thread's stack.

A: The stack contains all the local variables and all active method invocations.
The heap hold everything else.
As for your sub question: it means a new stack is created with its own dedicated memory.
While your new thread will share the total heap space (memory) allocated by the jvm

A: The heap is split up into multiple generations.
The bytecode, and its corrosponding JIT compiled machine code lives in the so called permanent generation, along with interned Strings and other class data.
Even though it is called the "permanent" generation, it can still be garbage collected. Some libraries, frameworks and JVM languages generate bytecode at run-time, so the permanent generation sometimes need clean up. Just like the other generations of the heap, but (one usually hopes) less frequently.

A: The actual bytecode and/or JIT'd code would live in the process's memory. There would likely only be one copy of it in the process memory, as all threads in a given process share that memory. Any variables shared by those threads will be accessed by the methods in common. Variables local to the threads (even method local variables used within a thread) will be created within that thread's memory.


text:
Q: access URL parameters without cookies My application should work without cookies. How can I get the parameters of the URL from a java file if cookies are disabled.
req.getParameter("abc") gives null when I tried.
I've 3 spring GenericFilterBeans in this application and I can see the values inside filters. How can I make the parameters available to others controllers and other files..

A: The presence and accessibility of the request parameters is completely unrelated to the cookie support.
The cause of your problem lies somewhere else. Probably a programmatic redirect was involved which caused the parameters to lost. Or the request was modified/wrapped/replaced in an improper manner. Verify your filters.


text:
Q: Finding Electric Field outside a Charged Cylinder I'm trying to solve a problem that involves finding the electric field due to a uniformly cylinder of radius $r$, length $L$ and total charge $Q$. Well, my thought was: if I am to use Gauss' Law, I'll have to use a gaussian surface enclosing the cylinder.
Then here arises my doubt: My try was to enclose the cylinder with another cylinder with radius $R > r$, parametrize it and find it's normal $\hat{n}$ at each point. Then, I would need to calculate $\mathbf{E}\cdot \hat{n}$ and integrate. This would only be good to calculate $\mathbf{E}$ if it's magnitude is constant on the gaussian cylinder so that the magnitude would drop out of the integral. Also, I would need $\mathbf{E}$ parallel to the normal. It seems that both those things are true, but how can I see it and justify/prove it?
I just want suggestions, hints, in how can I see/prove that $\mathbf{E}$ has constant magnitude on the gaussian cylinder and how can I see/prove that $\mathbf{E}$ is parallel to the normal at each point. I also thought on some argument arround symmetry but I didn't find any consistent one.
Thanks in advance for your help!

A: Symmetries! Your system system has radial symmetry. You can use cylindrical coordinates, with the $z$ axis being the charged cylinder axis; you will easily observe that, due to the symmetry of the system, every quantity depends only on $r=x^2+y^2$ and $z$, rather than $x$, $y$, $z$. The answers to your questions can be easily derived from this fact.

A: For external points, cylinder behaves like a line of charge. So you just have to put the distance in the formula of electric field of a point charge as (radius + distance from the cylinders surface)


text:
Q: jQuery/CSS - Password strength meter using zxcvbn.js and backspace I've created a password strength meter using zxcvbn.js. You can demo it here:
http://codepen.io/anon/pen/QEakxV
(UPDATE: Revised working pen: http://codepen.io/anon/pen/dXdGwE)
When I type in a password, it seems to work correctly, i.e. the meter grows and changes color appropriately for the password strength as determined by zxcvbn. The problem comes when backspacing - deleting characters from the password. It, too, works initially, until I reach the last one or two characters. At that point, the meter stops decreasing and remains partially visible, the equivalent of perhaps a password strength of 10%, even when the percentage strength is 0. (For verification, there is a console.log statement that outputs the current password strength percentage to the console.)
So, there is either something wrong with the way I am determining the value in the password input control or there is some quirk or different way I need to handle the key-up event, whether in general or specifically when the key that is involved is the backspace key (delete key on my Mac).
Any ideas?  Thanks!
HTML
<form novalidate="novalidate" class="simple_form new_user" id="new_user" action="/users" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" />

    New Password
    <input id="user-prefs-password-new-input" class="password optional user-prefs-input form-control" type="password" name="user[password]" />

    <input type="submit" name="commit" value="Update" id="user-prefs-email-password-form-submit-btn" class="btn-success btn-sm btn-submit" />

</form>

JAVASCRIPT
$(document).ready(function() {

  var input = document.getElementById('user-prefs-password-new-input');
  var bar  = document.getElementById('user-prefs-password-new-strength-meter');

  input.addEventListener('keyup', function() {

    console.log('*** PASSWORD: ' + input.value)

    var analysis = zxcvbn(input.value);

    var strengthPercentage = Math.floor(Number((analysis.guesses_log10 / 12.0).toFixed(2).replace(/0+$/, '')) * 100.0);
    if (strengthPercentage > 100) {
      strengthPercentage = 100;
    };

    console.log('*** STRENGTH PERCENTAGE: ' + strengthPercentage.toString())
    if ($(input).val() === '') {
      bar.style.backgroundImage = 'linear-gradient(to right, #ffffff 100%)';
    } else {
      switch (analysis.score) {
        case 0:
          bar.style.backgroundImage = 'linear-gradient(to right, #d30202 ' + strengthPercentage + '%, #ffffff ' + (strengthPercentage + 1) + '%)';
          break;
        case 1:
          bar.style.backgroundImage = 'linear-gradient(to right, #d30202 25%, #f07906 ' + strengthPercentage + '%, #ffffff ' + (strengthPercentage + 1) + '%)';
          break;
        case 2:
          bar.style.backgroundImage = 'linear-gradient(to right, #d30202 25%, #f07906 50%, #f3f304 ' + strengthPercentage + '%, #ffffff ' + (strengthPercentage + 1) + '%)';
          break;
        case 3:
          bar.style.backgroundImage = 'linear-gradient(to right, #d30202 25%, #f07906 50%, #f3f304 66%, #5bb502 ' + strengthPercentage + '%, #ffffff ' + (strengthPercentage + 1) + '%)';
          break;
        case 4:
          if (strengthPercentage <= 99) {
            bar.style.backgroundImage = 'linear-gradient(to right, #d30202 25%, #f07906 50%, #f3f304 66%, #57ad02 83%, #02ad02 ' + strengthPercentage + '%, #ffffff ' + (strengthPercentage + 1) + '%)';
          } else {
            bar.style.backgroundImage = 'linear-gradient(to right, #d30202 25%, #f07906 50%, #f3f304 66%, #57ad02 83%, #02ad02 100%)';
          };
      };
    };

  });

});

CSS
#user-prefs-password-new-strength-meter {
  width: 100%;
  height: 1em;
  margin-bottom: 1em;
  background-color: #ffffff;
  border: 1px solid #cccccc;
  border-radius: 0.25rem;
}

form {
  width: 30%;
  margin: 1em auto;
}

A: Can you try just removing the backgroundImage completely, like this:
if ($(input).val() === '') {
  bar.style.backgroundImage = 'none';
} else {
  ...
}

A: Add if statement after switch case.
  case 4:
              if (strengthPercentage <= 99) {
                bar.style.backgroundImage = 'linear-gradient(to right, #d30202 25%, #f07906 50%, #f3f304 66%, #57ad02 83%, #02ad02 ' + strengthPercentage + '%, #ffffff ' + (strengthPercentage + 1) + '%)';
              } else {
                bar.style.backgroundImage = 'linear-gradient(to right, #d30202 25%, #f07906 50%, #f3f304 66%, #57ad02 83%, #02ad02 100%)';
              };
          };
        };
//Add this below if statement,
         if (strengthPercentage <= 10){
              bar.style.backgroundImage = "none";
         }
      });

A: Or, you could just fix the issue when the input is empty...
bar.style.backgroundImage = 'linear-gradient(to right, #ffffff 100%, #ffffff 100%)';


text:
Q: How to hide PDF file on my website from bots with reCaptcha? I'm currently trying to share a PDF document on my personal website.
When it's not a problem to do it I need to hide it from bots.
I tried to use google's Invisible reCAPTCHA but had some issues.
Web-crawlers can search through source code so inactive button doesn't work.
Do I need a special page to check if reCAPTCHA is done? Maybe is there an easy way to always show  link but hide link HREF or form ACTION attribute (maybe with PHP help) when non-human is found?
        <form id="resume" action="subpage_that_shows_my_pdf_file_link.html" method="POST">
            <button class="g-recaptcha" data-sitekey="666" data-callback="onSubmit" type="submit">Submit</button>
        </form>

Actually google docs are not helping with this.

A: Ok, I did it with captcha-response. My main parts of code:
index.php
        <form id="reCaptchaForm" action="file.php" method="POST">
            <button class="g-recaptcha" data-sitekey="..." data-callback='onSubmit' >link</button>
        </form>

file.php
if(isset($_POST['g-recaptcha-response'])) {
$secretKey = '...';
$response = $_POST['g-recaptcha-response'];
$remoteIp = $_SERVER['REMOTE_ADDR'];
$reCaptchaValidationUrl = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$remoteIp");
$result = json_decode($reCaptchaValidationUrl, TRUE);
if($result['success'] == 1) {
    $userMessage = '<meta http-equiv="refresh" content="0;URL='file.pdf'" />';
}

On special page code is displayed only if in this particular session google invisible captcha says yes, looks like a normal user :)


text:
Q: How to set year to 2020 if there is no year set on a VARCHAR date I'm working with a quite old database... And dates are stored as VARCHAR, and I need to keep dates as VARCHAR :S but expanding it with year=2020, hour=0, minute=0, and second=0 if that fields are not set.
Dates have all kind of weird formats, such as '01/08', '01/08/20', '01/08/2020' and so on. I'm dealing good with all formats, except when year is not set, I have tried with this query, but it set the year to 0 and causes an error with STR_TO_DATE() function
UPDATE people
SET date =
    IF (
        YEAR(STR_TO_DATE(date, '%d/%m/%Y %H:%i:%s')) > 0 ,
        DATE_FORMAT(STR_TO_DATE(date, '%d/%m/%Y %H:%i:%s'), '%d/%m/%Y %H:%i:%s') ,
        DATE_FORMAT(STR_TO_DATE(date, '%d/%m/%Y %H:%i:%s') + INTERVAL 2020 YEAR, '%d/%m/%Y %H:%i:%s')
    )

Any idea dudes?


text:
Q: Copiar parte do Dataframe onde coluna é Nulo ou NaN Estou com a seguinte dúvida.
Tenho o seguinte dataframe de exemplo:
import pandas as pd
df = pd.DataFrame({'A' : [4,5,13,18], 'B' : [10,np.nan,np.nan,40], 'C' : [np.nan,50,25,np.nan], 'D' : [-30,-50,10,16], 'E' : [-40,-50,7,12]})

df

Oque pretendo fazer é:

*

*A partir da coluna B quero verificar em quais linha a coluna B é 'NAN' e caso seja, quero criar um outro dataframe contendo as mesmas colunas do atual (df), porém somente com as linhas de índice 1 e 2 (nesse caso).

Para exemplificar melhor, o resultador deveria ser:
df2

Tentei inicialmente utilizar o comando loc
df2 = df.loc[:]

porém, não consegui referência de como só buscar os valores np.Nan, existe alguma maneira de fazer isso?
Testei com os campos  nulo do pandas para ver o resultado.
    import pandas as pd
df = pd.DataFrame({'A' : [4,5,13,18], 'B' : [10,'','',40], 'C' : ['',50,25,''], 'D' : [-30,-50,10,16], 'E' : [-40,-50,7,12]})

E utilizando a sintaxe:
df2 = df[pd.isnull(df).any(axis=1)]

esse comando funciona porém busca linhas em branco em qualquer coluna, como poderia mudar ele para pegar uma unica coluna?

A: Podes utilizar uma das três opções:
op_a = df[df['B'].isnull()] # mesmo resultado com: isna()
# ou
op_b = df.loc[df['B'].isnull()] # mesmo resultado com: isna()
# ou
op_c = df.query('B != B')

ambas terá a saída:
   A    B     C   D   E
1  5  NaN  50.0 -50 -50

DataFrame utilizado como exemplo:
{
  'A' : [4,5,13,18],
  'B' : [10,np.nan,'',40],
  'C' : [np.nan,50,25,np.nan],
  'D' : [-30,-50,10,16],
  'E' : [-40,-50,7,12]
}

Podes ser visto funcionando em repl.it


text:
Q: How does the state updates of objects in React work accurately I am learning React, and trying to wrap my head around the syntax, and concepts.    From the tutorials of React it is mentioned:

State Updates May Be Asynchronous
React may batch multiple setState() calls into a single update for
  performance.
Because this.props and this.state may be updated asynchronously, you
  should not rely on their values for calculating the next state.

My question is, if the this.state is not updated at all times, can we rely on it to show the right information?  If my understanding is correct, React will update this state in batches for performance reasons, but does it affect the accuracy of the application?  How does React create these batches and when do they get applied?

A: React uses state to help manage each piece of component with javascript. Since state can always change it makes it really flexible. One downside is that since it is flexible it can be hard to manage the state when there are multiple objects. It is ideal to keep components in manageable pieces so that you can locate when a state is not behaving as expected.
To prevent data from mutating unexpectedly, tools/concept such as ImmutableJs or Redux have been combined with React to make managing tools more efficent.
Redux controls/organizes where pieces of state changes through a one-directional flow. http://redux.js.org/docs/basics/UsageWithReact.html
ImmutableJs uses persistent immutable data structures which locks state to prevent unexpected changes. https://facebook.github.io/immutable-js/

A: React will render component with updated state as soon as it is reasonable - for example in event handlers you are able to change state of multiple components, however it is not reasonable to render them with new state separately - instead React will batch updates and render components after event handler finishes.
In correctly written application delay between update and render will be unnoticeable for user. From developer perspective asynchronous updates may introduce hard-to-find bugs (using Redux where every state update is based on previous state should solve most of them; this is of course possible also in pure React by using setState() with callback).

A: State being asynchronous does not mean that you can't rely on it, but you should be careful how and when you are using the information you are keeping there.
For example:
this.setState({charCount: 5});
console.log(this.state.charCount) // may not be 5 as setState is asynchronous

On the other hand you can use callback to be sure that you got a correct value:
this.setState({charCount: 5}, () => { console.log(this.state.charCount) });

General practice is that you should try to minimize the use of state and only use it, when changes are needed on user interface. If you need to process or manipulate data without UI changes try to avoid using state and use for example this practice: Lifting State Up


text:
Q: RavenDB DeleteByIndex and BulkInsert in replication scenario What I need to do is deleting an entire Collection of items and importing a new set of data.
The new set of data contains both new items and existing items (same id of the deleted items).
I need to do this on a server having Master-Master replication active with another server, so this is the scenario:
Server1 and Server2 in Master-Master replication.
I delete and bulk-insert data on Server1, the data are replicated on Server2.
This is what I'm doing at the moment:
Step 1.
Insert 50000 records in Server1.
List<Test> data = new List<Test>();

for (int i = 1; i <= 50000; i++)
{
    var t = new Test();
    t.Id = "Tests/" + i.ToString(); // NOTICE THIS
    t.Name = "Test" + i.ToString();
    t.Description = "Test nr. " + i.ToString();
    t.Time = DateTime.Now.TimeOfDay.ToString("hhmmssff");

    data.Add(t);
}

using (var bulkInsert = docStore.BulkInsert(options: new Raven.Abstractions.Data.BulkInsertOptions() { CheckForUpdates = true, BatchSize = 1024 }))
{
    foreach (var d in data)
    {
        bulkInsert.Store(d);
    }
 }

The 50000 items are correctly inserted and than replicated into the Server2, so I have 50000 records in both Server1 and Server2 now.
Step 2.
I launch a procedure to delete the 50000 items collection in Server1 and to insert a new set of 500 items.
// DELETE
var op = docStore.DatabaseCommands.DeleteByIndex("Raven/DocumentsByEntityName", new IndexQuery { Query = "Tag:" + "Tests" }, allowStale: false);
op.WaitForCompletion();

// INSERT
List<Test> data = new List<Test>();

for (int i = 1; i <= 500; i++)
{
    var t = new Test();
    t.Id = "Tests/" + i.ToString(); // NOTICE THIS, SAME IDs DELETED ABOVE
    t.Name = "Test" + i.ToString();
    t.Description = "Test nr. " + i.ToString();
    t.Time = DateTime.Now.TimeOfDay.ToString("hhmmssff");

    data.Add(t);
}

using (var bulkInsert = docStore.BulkInsert(options: new Raven.Abstractions.Data.BulkInsertOptions() { CheckForUpdates = true, BatchSize = 1024 }))
{
    foreach (var d in data)
    {
        bulkInsert.Store(d);
    }
}

When this procedure starts, I correctly see in both servers that the Tests items are getting deleted, I see the documents decreasing in both servers.
When the collection in Server1 is completely deleted, the Insert procedure starts, but when this happens, the Server2 collection is not empty yet.
Let's say that when the Server1 delete operation completes, there still are 10000 items in the Server2 collection.
The Insert operation on Server1 starts now, and the inserted data begin to be replicated.
What happens in Server2 is that the Delete operation is stopped and the new 500 items are inserted, so when the procedure is complete I have 500 items on Server1 (from ID 1 to ID 500) and 10500 items on Server2.
If I delete the collection on Server1 now (from Raven Management Studio), the 500 items are deleted from the Server2, so I have no items in Server1 and 10000 items in Server2.
I also tried to combine DeleteByIndex "WaitForCompletion" setting and BulkInsert "CheckForUpdates" setting with the following results:
1.
DeleteByIndex.WaitForCompletion = true
BulkInsert.CheckForUpdates = true

Result:
the delete replication is stopped in Server2 when Insert starts on Server1 (this is the case explained above)
2.
DeleteByIndex.WaitForCompletion = true
BulkInsert.CheckForUpdates = false

Result:
the delete replication is stopped in Server2 when Insert starts on Server1 (same as above)
3.
DeleteByIndex.WaitForCompletion = false
BulkInsert.CheckForUpdates = true

Result:
I receive a concurrent modification error when Insert starts.
The delete is completed in both servers, so I have no data on both server at the end of the procedure.
4.
DeleteByIndex.WaitForCompletion = false
BulkInsert.CheckForUpdates = false

Result:
I receive an illegal duplicate key error when Insert starts,
The delete is completed in both servers, so I have no data on both server at the end of the procedure.

Can someone suggest the best way to manage this situation?
I recap the goal:
I need to completely delete one collection and importing new data in a Mster-Master replication scenario.
The new data can be completely new items or previously existing data.
Thanks in advance.


text:
Q: Can't find spreadsheet on GoogleDrive which was created by google_drive gem / learn-Rails tutorial I'm trying to complete the learn-Rails tutorial and I have come across a problem implementing the writing of visitors recording in a GoogleDrive spreadsheet as depicted in the tutorial which actually refers to outdated procedures of loggging to the GoogleDrive spreadsheet.
Since userID / password aren't supported anymore I created a service account at Google as suggested by the google_drive gem docs and successfully connected from Rails to my spreadsheet this way:
def update_spreadsheet
    connection = GoogleDrive::Session.from_service_account_key("SpreadSheet-acd8a78038a0.json")
    ss = connection.spreadsheet_by_title('Learn-Rails-Example')
    if ss.nil?
        ss = connection.create_spreadsheet('Learn-Rails-Example')
    end
    ws = ss.worksheets[0]
    last_row = 1 + ws.num_rows
    ws[last_row,1] = Time.new
    ws[last_row,2] = self.name
    ws[last_row,3] = self.email
    ws[last_row,4] = self.content
    puts "Current num rows: "+last_row.to_s
    ws.save
 end

Everythig runs fine in my Rails app but I can't access the spreadsheet from GoogleDrive in my Chrome browser despite the fact that the spreadsheet actually exists somewhere since I noticed num_rows increrements at console log each time I add a contact within the app.
If I can't see the spreadsheet directly in Google Drive from Chrome then it's bad news since I'd need to write a separete Ruby app to download the data.

A: At last I found the solution:

*

*I created a Learn-Rails-Example spreadsheet (it was the name given by Rails) manually in my Google Drive

*I shared that doc with the client_email of my service account (webserve@spreadsheet-61909.iam.gserviceaccount.com)

*I Lunched the Rails app and noticed that from now on the spreadsheet was update and visible to Google Drive in Chrome browser.
Problem solved!


text:
Q: Check if there are existing records in the iCloud I want to add default entries at the first start if the app was never installed or the app is deleted from the iCloud.
The problem is: at the moment it merges with duplicates because on the first start of the app it adds new default entries.
Is there a way to detect if there are entries in the iCloud acc from the user?

A: func doesRecordExist(inRecordType: String, withField: String, equalTo: String, _ completion: @escaping (Bool) -> ()) {
    print(withField,equalTo)
    var result = false

    let predicate = NSPredicate(format: "\(withField) == %@", equalTo)
    let query = CKQuery(recordType: inRecordType, predicate: predicate)
    publicDatabase.perform(query, inZoneWith: nil, completionHandler: {results, er in

        if results != nil {
            print(results!.count)
            if results?.count == 1 {
                print(results!.count)
                result = true
            }
        }
    })
    completion(result)
}


text:
Q: best theory on fitting mixture of gaussians What are the current best results on fitting mixtures of Gaussians with any algorithm (EM or something fancier)? Specifically, if I know only the number of components, what are the sharpest sample complexity bounds for recovering the mixture weights, the means, and the covariances?
I'm looking for an entry into the literature, so if there are particularly well-written and relative up-to-date papers that have a strong pedagogical / survey aspect to them, I'd appreciate pointers in those directions too.