Lubuntu 20.04 freezes

Question: I have recently installed Lubuntu 20.04 on a MacBook Air (2011).
From the beginning it froze practically every time I start it about half of the time it freezes even while trying to do the Login.

After implementing @heynnema's answer...
swapon -s
Filename                                Type            Size    Used    Priority
/swapfile                               file            4194300 3328    -2

free -h # confirm 2G RAM and 4G swap
              total        used        free      shared  buff/cache   available
Mem:          1,8Gi       926Mi       174Mi       139Mi       731Mi       548Mi
Swap:         4,0Gi        15Mi       4,0Gi

Comment: Edit your question and show me `free -h` and `grep -i swap /etc/fstab`. Start comments to me with @heynnema or I'll miss them.
Comment: Sorry I missed your updates. You didn't notify me with a comment that started with @heynnema. Funny enough, `free -h` shows a 2G swap, but the `grep` doesn't show any swap lines in /etc/fstab. Curious. Show me `swapon -s` and `sudo blkid`.
Comment: Are you up to date on your MacBook Air BIOS/firmware updates?
Comment: @heynnema: $ swapon -s
Filename                                Type            Size          Used       Priority
/dev/sda3                               partition       2006012   141056    -2
Comment: Please add the output of my two commands as an edit to your original question, not in the comments, please. Also show me `cat /etc/fstab` and `sysctl vm.swappiness`.
Comment: @heynnema, thanks a lot for your help! Sorry, but I don't know what "BIOS/firmware updates" are - I'm always installing the updates for the OS (I have only Lubuntu installed).
Comment: You'll have to go to the MacBook Air support/downloads web page and look for the BIOS/firmware updates there. Apple doesn't call it BIOS... but I can't remember what their naming is. Add the four commands output to your question please.
Comment: Why not use Apple's Mac OS X instead of Lubuntu?
Comment: @heynnema, Sorry, but I can't see the four commands. The Mac OS X versions, which still get support do not work on this hardware, as the latter is too weak to deal with the extensive data requirement of the current Mac OS x's.
Comment: What "four commands" are you asking about? Also, see my minor edits to my answer to help you with the editing.
Comment: @heynnema, You wrote: "... Add the four commands output to your question please." I don't understand what you mean. The same goes for: ".., see my minor edits to my answer to help you with the editing." I don't see what you edited. I'm really sorry for all this trouble!
Comment: Do you need a `swappiness` value so high??  I realize you have very little RAM (I avoid using a thinkpad I have with only 2GB of ram) but with it that high it'll constantly want to swap memory in/out  (system will pause with disk light solid-on, or flashing very fast depending on your firmware)
Comment: @guiverc , thank you for your input. To answer your question: I don't know. If you think a lower value might be more likely to solve the problem, how much would you suggest?
Comment: I would normally boot a *live* system (eg. Lubuntu install media) on a system with 2GB of RAM (I have a thinkpad sl510 with that) & do some testing. I don't have time currently to do it, but I doubt a value of 80 would be best (default=60, higher value means it swaps RAM out to disk more often.. ie. encouraging *thrashing* is my concern, where *thrashing* will be a problem with that little RAM if you use a web browser). That however relates to operation, and should not impact login (I tested login on 19.04 with laptops with only 1GB of RAM without issue; 20.04 with 2GB).
Comment: Login can *feel* slow (and I'd disable *snaps* on 2GB if you're not going to need them; this will speed up login), but a slow login is not a freeze (a freeze I take it as being many minutes long), and a slow login shouldn't impact operation. Your results are inconsistent though; you mention swappiness as **60** (system default) once & **80** once (what grabbed me as excessive!) so maybe what I noticed was just a typo.
Comment: @guiverc , Login is not unusually slow, but the freezes are pretty much permanent - until I shut it down and start again.
Comment: I tried to work with swappiness 60, but it did not improve the issue. With the previous LTS version it never froze.
Comment: Previous I take it as 18.04 LTS, were you using the GA or HWE kernel?  Did you re-install or upgrade (problems on upgrade were to be expected it said in the release notes due to desktop change).  I'd boot install media (20.04 & 20.04.2 media) & try using that to see if you get your 'freezing'... If you were using the GA (4.15) kernel it maybe an issue with a 5.4/5.8 kernel module (ie. driver); which kernel are you using? (20.04 with GA = 5.4, 20.04 with HWE is 5.8 currently)
Comment: @guiverc , I don't know which kernel the 18.04 LTS OS was working with, nor which I am using now. I did a re-install for 20.04. How can I find out which kernel I'm using?
Comment: `uname -r` will provide details of the currently running kernel. A 20.04 system will report 5.4 for a GA kernel being used and 5.8 for a system on the HWE kernel  (note: that's current; HWE upgrades during the life of the system and will *bump* next to 5.10 but that hasn't occurred yet)
Comment: @guiverc , uname -r
5.4.0-66-generic
Comment: @guiverc Regarding your prior comment about vm.swappiness... please note my answer... I had OP increase /swapfile, and increase vm.swappiness, to, as you say, with only 2G RAM... increase swapping, intentionally. OP hasn't been able to complete my answer yet.
Answer: Your big problem is that you only have 2G RAM. Best to add more RAM if possible.
In the mean time, let's modify your current swap setup. We change from using a 2G swap partition, to a 4G /swapfile. And we modify vm.swappiness to increase swapping.
/swapfile
First we create a 4G /swapfile...
Note: Incorrect use of the dd command can cause data loss. Suggest copy/paste.
In the terminal...
sudo swapoff -a           # turn off swap
sudo rm -i /swapfile      # remove old /swapfile

Note: or sudo swapoff /dev/sda3 and skip the sudo rm...
sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

sudo chmod 600 /swapfile  # set proper file protections
sudo mkswap /swapfile     # init /swapfile
sudo swapon /swapfile     # turn on swap
free -h                   # confirm 2G RAM and 4G swap

Now edit /etc/fstab, using sudo -H gedit /etc/fstab or sudo pico /etc/fstab.
Add this /swapfile line at the end of /etc/fstab (use spaces, not tabs)...
/swapfile  none  swap  sw  0  0

Then save the file and...
reboot                    # reboot and verify operation

2G swap partition
sudo swapon -s may still show /dev/sda3 as your swap.
sudo swapoff /dev/sda3 # disable disk partition swap
Use gparted to delete /dev/sda3.
reboot
vm.swappiness
Then we increase swapping...
Now edit /etc/sysctl.conf, using sudo -H gedit /etc/sysctl.conf or sudo pico /etc/sysctl.conf.
Add vm.swappiness=80 to the end of /etc/sysctl.conf and reboot.
Finally...
Confirm that this is all working with these commands...
free -h or swapon -s
and confirm 4G /swapfile.
And...
sysctl vm.swappiness should show 80.
Comment: I don't understand how to: "Confirm this /swapfile line at the end of /etc/fstab" and how to: "Add vm.swappiness=80 to the end of /etc/sysctl.conf and reboot."
Comment: @manoka 1) Use one of the two edit commands that I gave as an example. Then add the /swapfile line. 2) Use similar command(s) to edit /etc/sysctl.conf and add the highlighted string at the end of that file.
Comment: Sorry, I also don't understand how to do everything after "Finally...".
Comment: @manoka You did something wrong, as the swap looks broken now. Edit your question and show me `free -h` and `swapon -s` and `cat /etc/fstab` and `ls -al /swapfile` and `sudo fdisk -l /dev/sda`. Add this output to the END of your question and I'll take a look what went wrong.
Comment: @manoka You forgot to edit /etc/fstab and add `/swapfile  none  swap  sw  0  0`. Please re-read my answer for details. Report back. Also, when updating your question with new data, make sure to send me a comment that starts with "@heynnema", without the quotes, or I'll miss your updates.
Comment: Sorry, but I don't know exactly how "to edit /etc/fstab and add /swapfile  none  swap  sw  0  0". Do you mean to execute the command like this: "sudo pico /etc/fstab/swapfile  none  swap  sw  0  0", or should I execute the command "sudo pico /etc/fstab" first, and then add "/swapfile  none  swap  sw  0  0" somewhere to the output?
Comment: @manoka The latter. Use either edit command to open the file. `gedit` is probably easier for you. Then add "/swapfile none swap sw 0 0" to the end of the file. Then reboot. Then do `free -h` and confirm a 4G swap.
Comment: When I execute the command "sudo pico /etc/sysctl.conf" I get this output (see at the end of my question) - and I seem to be unable to add anything there.
Comment: @manoka That's why I suggested that you use the `gedit` command instead of the `pico` command... it'll be easier for you.
Comment: I added "/swapfile none swap sw 0 0" to the end of the gedit file. I pasted the output of "free -h" at the end of my question. But I don't know how to "confirm a 4G swap".
Comment: @manoka Show me `tail /etc/fstab` and `tail /etc/sysctl.conf` and `sysctl vm.swappiness`. Then reboot. Do `free -h` and the output should indicate 2G RAM and 4G swap.
Comment: I did what you recommended and added the requested outputs to the end of my question.
Comment: @manoka I don't see the new outputs in your question.
Comment: @manoka Oh, there they are... we've discussed this before... don't edit my answer... edit new outputs into your original question.
Comment: @manoka The edits don't show up in /etc/fstab, so your /swapfile is still not working at all. The edits to /etc/sysctl.conf look fine.
Comment: what can I do that /etc/fstab will work.
Comment: @manoka Just follow the detailed instructions that I left for you. Edit the file with `sudo -H gedit /etc/fstab`, add the /swapfile line that I show, save the edits, reboot. Very simple.
Comment: I did everything from your instructions from "vm.swappiness" to the end. The outputs I pasted to the end of my question. Unfortunately when rebooting it freezed for the first time even before the login page appeared.
Comment: @manoka The errors that you received when doing `sudo -H gedit /etc/fstab` are just noise, due to a different bug, but it shouldn't stop you from editing /etc/fstab and adding the `/swapfile  none  swap  sw  0  0` line at the end, saving the edit, then rebooting.
Comment: @manoka Status please...
Comment: it still freezes (sometimes preceeded by dropouts), although not so often during login, but more often after some time of surfing.
Comment: @manoka Let's verify where you're at right now. Edit your question and show me `grep -i swap /etc/fstab` and `grep -i vm.swappiness /etc/sysctl.conf` and `free -h`.
Comment: I added the requested outputs to the end of my question. I just noticed that the issue has something to do with having two different browsers open at the same time. When I'm using only one, the system works a lot faster and with less freezing. I also removed a brave browser, which I installed according to commands of an unofficial website - as I could not find the software catalog after I installed Lubuntu 20.04 LTS. I will let you know how it works within 24 hours.
Comment: @manoka Your /etc/fstab now looks fine. Your vm.swappiness looks fine. But your swap still isn't working. Show me `swapon -s`... it should say `/swapfile`. You may have to recreate the 4G /swapfile following my instructions.
Comment: @manoka Have you rebooted since fixing /etc/fstab? If not, reboot, and that might get your /swapfile to work.
Comment: I added the requested outputs below my question.
Comment: @manoka Hurrah! It's finally working. Good job! The reboot fixed it. If my answer helped to solve the problem, please remember to accept it by clicking on the checkmark icon that appears just to the left of my answer. Thanks!
Comment: thank you so much for all your patience and efforts! The system is now working without issues. Though I wonder whether this was a shortcoming of the new Lubuntu version, or whether it is just an issue due to a particular hardware. I wish I could do something for you in return - if I could, please don't hesitate to let me know!
Comment: @manoka Glad it's all working as it should :-)

Lubuntu 20.04 freezes


How can I automatically delete dates and times in rows with EmEditor?

Question: I have a text file.
There are hundreds of different filenames in the text file.
However, it says different date and time at the end of each file.
Sample: life-in-cosmos-2021-11-11-12-45-46 or life-in-cosmos-2021-11-11-12-45.
In order to change the names of the files in bulk, I first need to delete the dates in this text file.
So I want to automatically delete the dates and times in each row.
However, I don't know anything about this.
And I don't know how to use macros.
Therefore, if there is a solution for this, can you provide an answer with a picture or video?
In order to explain my request more clearly, I present 2 examples.
Example:
Original Text: cosmos-lights-colors-T5DAPC-2020-09-11
The result I want to do: cosmos-lights-colors-T5DAPC
Example 2:
Original Text: cosmos-lights-colors-T5DAPC-2021-04-02-12-37-49-utc
The result I want to do: cosmos-lights-colors-T5DAPC
Comment: Can you please write a sample file exactly (but simplified way)?
Is your file content like this: ?
`life-in-cosmos-2021-11-11-12-45-46 (NEWLINE) life-in-cosmos-2021-11-11-12-45`  What is your exptected result? Is your expected result like this? `life-in-cosmos- (NEWLINE) life-in-cosmos-`
Comment: Thanks for updates. You have only one file to edit? Is a date always at the end of each line? No characters exist after each date (except `-utc`)?
Answer: Assuming a date is always at end of each line, you can replace a regular expression with an empty string. To do this:

Press Ctrl+H to bring up the Replace dialog box, and set following options:

Find: -[0-9]{4}-[0-9]{2}-[0-9]{2}[0-9\-]*?(\-utc){0,1}$
Replace with:  (blank)
Set the Regular Expressions option

First, click the Find Next button to highlight matches to make sure they are correct. If the matches are incorrect, you will need to adjust the regular expression.

Finally, click the Replace All button to remove all matched strings.

Before replace
cosmos-lights-colors-T5DAPC-2020-09-11
cosmos-lights-colors-T5DAPC-2021-04-02-12-37-49-utc

After replace
cosmos-lights-colors-T5DAPC
cosmos-lights-colors-T5DAPC

Comment: It worked, thank you. Now I'll have to do some research before I can bulk change the file names with this data.


How to manually import the pool and exit in ZFS filesystem?

Question: When I tried to power on the Ubuntu 19.10 I am seeing this error message:
Failed to import pool 'rpool'.

Command: /sbin/zpool import -c /etc/zfs/zpool.cache -N 'rpool'
Message: cannot import 'rpool': one or more devices is currently unavailable. Error: 1

Manually import the pool and exit.

Few hours ago, I used my laptop normally in the CCNA class without any issue. But when I return home, I started to see that message.
 Using live 19.10 bootable pen drive, I can get the output of sudo zpool import. But don't know how to repair and what's wrong.
Let me know if need more output to help.
Answer: A bit late replay, but I want to pitch in how I ended up solving above problem:
Apparently, my hard disk my reaching its lifespan limit. This might not be in your case if you haven't experience this quite often as I did. There was always something wrong with my hard disk and it keep failing.
After discussing in several other communities and hard disk test, I came to a conclusion that its time to change hard.
So I bought SSD, reflash Ubuntu. Problem solved.


Handle Squirrel's event on an Electron app

Question: These days I'm toyng around with Electron to build a small native app for Windows and I'm using Grunt Electron Installer to create an installer for my application.
The installer is created successfully but I don't know how ho handle Squirrel's events inside my app, as stated in the docs I've added this to the entry point of my app:
var handleStartupEvent = function() {
    if (process.platform !== 'win32') {
        return false;
    }

    var squirrelCommand = process.argv[1];
    switch (squirrelCommand) {
        case '--squirrel-install':
        case '--squirrel-updated':

            // Optionally do things such as:
            //
            // - Install desktop and start menu shortcuts
            // - Add your .exe to the PATH
            // - Write to the registry for things like file associations and
            //   explorer context menus

            // Always quit when done
            app.quit();

            return true;
        case '--squirrel-uninstall':
            // Undo anything you did in the --squirrel-install and
            // --squirrel-updated handlers

            // Always quit when done
            app.quit();

            return true;
        case '--squirrel-obsolete':
            // This is called on the outgoing version of your app before
            // we update to the new version - it's the opposite of
            // --squirrel-updated
            app.quit();
            return true;
    }
};

if (handleStartupEvent()) {
    return;
}

But I don't know what to do inside this switch statement to, for example, create shortcuts for my application. Actually I don't even know if this switch works at all because when I install (or uninstall) my application it get launched and never quits.
Any help is appreciated!
Answer: You could handle each Squirrel event and create shortcuts:

  case '--squirrel-install':
          target = path.basename(process.execPath);
          updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
          var createShortcut = updateDotExe + ' --createShortcut=' + target + ' --shortcut-locations=Desktop,StartMenu' ;
          console.log (createShortcut);
          exec(createShortcut);
          // Always quit when done
          app.quit();
          return true;

case '--squirrel-uninstall':
            // Undo anything you did in the --squirrel-install and
            // --squirrel-updated handlers
            target = path.basename(process.execPath);
            updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
            var createShortcut = updateDotExe + ' --removeShortcut=' + target ;
            console.log (createShortcut);
            exec(createShortcut);
            // Always quit when done
            app.quit();
            return true;
Comment: Is `update.exe` something related to squirrel or is it some custom exe you made? as I cannot find any info on what or where this update lives (other than your single post here).
Comment: I just invoked Update.exe from the command-line to see all the supported commands.
Comment: Thanks, now I can see the properly shortcuts on my desktop and start menu. If I might ask where did you find those commands? I did look in Squirrell for Windows docs and didn't find anything useful...


What is a  in Mongo_url to connect meteor app

Question: so sorry for my ignorant question, but im really new to meteor, and still tryina figure everything out. so I want to connect my app to galaxy hosting, and to do that I got a Mongo_url. But the thing is I dont know what a dbname is, I understand it is a database name, but I dont know what to repalce it with in my app. Im using atlas for the mongodb, so I tried to put it in like that but it didnt work. so just tried to put it in the way it was, and it didnt work. so i replaced it with "meteor" like this:
<code>mongodb+srv://abidmir:<password>@cluster0.6fk1x.mongodb.net/Meteor(<dbname>, did not accually put this, just left the meteor part)?retryWrites=true&w=majority
</code>
but it didnt work, and I figured it was probably because I didnt put in the proper thing. I would really appreciate any help!
Answer: The URI that Atlas gives you is supposed to have the database name in it, that is the database name you need to use.
Comment: in the link I got, it just said  and said that just put the data base name here. were can i  find the database name?
Comment: If you haven't created a database in Atlas I'm guessing you can put in any database name you want.
Comment: how do you create a database in atlas, and is it free?


What is the best file system on top of LVM encryption?

Question: On my (early SSD) laptop I normally choose to put everything in an encrypted LVM because I'm a bit paranoid. :) I assume that all of the great performance features of the file systems such as ext4 assume a lot about the distribution of data that simply isn't true when there's an encryption layer on top. To that end, what is the best file system on top of a layer of encryption? Is it JFS since it "does less" and there for is computationally less expensive?
Comment: Yes.
Comment: What do you mean "assume a lot about the distribution of data..."?  Encryption does not alter the placement of data.
Comment: Are you saying that LVM encryption is performing encryption on small blocks at a time?
Comment: So is your answer that it doesn't matter? I don't know enough about the mechanics of LVM encryption to answer this myself, though you appear to be an expert :)
Comment: @Maike Axiak: Yes.  The only difference encryption makes is that if you look at the raw disk, it looks like random garbage.  The FS does not know or care that encryption is in use.
Answer: dm-crypt doesn't depend on LVM. It can encrypt any block device, like CDs, even swap space.
It supports a bunch of modes of operation, some of which impact performance more than others, and all of which interact differently with the file system. The encryption doesn't necessarily operate using the same block size as the device itself: the XEX-TCB-CTS mode of operation (XTS) deliberately uses blocks that are not evenly divisible by the hardware block sizes, for example.
However, in reality, the overhead from the encryption is so large that it doesn't make any difference at all. I therefore recommend you choose your file system based on reliability considerations.
As maaartinus points out, if your CPU supports the AES-NI instruction set (cat /proc/cpuinfo to find out), encryption will be fast enough that it may make sense to test different filesystems. However the differences between various filesystems should still be comparable to using no encryption at all, and the usual advice would hold. I still recommend to choose a file system based on considerations of reliability, not speed.
Comment: I disagree, the overhead from encryption may actually be negligible and the setting may be important. For example, my computer can decrypt 3 GB/s while using AES and only about ten times less while using anything else (that's because of AES-NI; in both cases the overhead is quite low).
Comment: I didn't take AES-NI into account - however, what do you mean by "anything else"? You don't really have a choice but to use AES today, this discussion was about which file system to use with AES encryption.
Comment: *Sorry, I missed your point - the encryption overhead might indeed dominate the filesystem performance differences.* By anything else I mean the other two algorithms provided by Truecrypt (Twofish and Serpent), but this doesn't matter... the speed of other modern ciphers is quite similar; it's the HW support what makes AES much faster.
Comment: Great. On a side-note, I absolutely advise against using anything but AES for full disk encryption. The reason Twofish and Serpent haven't been broken yet might be, for all we know, that they haven't gotten enough attention by researchers, whereas AES is the focus of vast cryptoanalysis. The fact that AES-NI speeds it up dramatically hammers it home, AES is *the* cypher to use.


android cursor indicates row count 1 but throws exception 0 rows found

Question: Have you ever had a cursor tell you that it has data but immediately throw an exception when trying to access that data? No? I have and I am at my wits end.
Blow is the code that throws an exception. Below it I will add the Log Cat output.
protected void setValue(String qVal) {
    StringTokenizer tokenizer = new StringTokenizer(qVal,"|");
    String first = tokenizer.nextToken();
    if(first.equalsIgnoreCase("0"))
        return;
    String searchID = tokenizer.nextToken();
    String [] cols = {TempImageEntry.RawData, TempImageEntry.FileName};
    String selection = TempImageEntry.ID + "=" + searchID;
    Cursor cursor = mDatabase.getReadableDatabase().query(TempImageEntry.TABLE_NAME,cols,selection,null,null,null,null);
    boolean check = cursor.moveToFirst();
    if(!check)
    {
        cursor.close();
        Log.e(LOG_TAG,"Could not find image data!");
        return;
    }
    int temp1 = cursor.getColumnIndex(TempImageEntry.FileName);
    int count = cursor.getCount();
    Log.d(LOG_TAG,"Count:"+count);
    String FName = cursor.getString(temp1);
    byte [] rawData = cursor.getBlob(cursor.getColumnIndex(TempImageEntry.RawData));
    cursor.close();
    setImageData(rawData,FName);
    Log.d(LOG_TAG,"parsed image data");
}

Loggat output:
D/ImageHelper: Count:1
E/CursorWindow: Failed to read row 0, column 1 from a CursorWindow which has 0 rows, 2 columns.
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x40e94ac8)
E/AndroidRuntime: FATAL EXCEPTION: main
                  java.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
I've tried a clean rebuild of the code. nothing helps.
I extracted the database from the device, opened it in SQLite browser, entered the same query being generated by android, and I got back data.
Every other cursor in the app follows this exact same logic path and they all work.
I even took some variables out of inline into temp to see what they look like during runtime.
Thanks for any advice you can give
Comment: I bet that blob column is to big for CursorWindow ...
Comment: On sqlite >= 3.7.6 check blob length ... with `SELECT length(blob_column)` compare it with `Resources.getSystem().getInteger(
                com.android.internal.R.integer.config_cursorWindowSize)` * 1024 (i'm not sure if you can get this value - you can just assume that it is something about 1MB) ... if it's bigger then use `SELECT substr(blob_column, start, len)` in the loop for getting blob partially ... **or as it was written multiple times do not store blob in the sqlite itself but just save a file(fx with FileProvider from compat lib) and store only a path to it**
Comment: As I wrote "I bet" ... to check if I'm right change `cols = {TempImageEntry.RawData, TempImageEntry.FileName};` to `cols = {TempImageEntry.FileName};` and comment out getting blob data and replace `setImageData(rawData,FName);` with `setImageData(null,FName);` ... if it would work (or crash later with NPE in `setImageData`) then the problem is with blob size .... alos I'm not getting *when trying to even read the string which contains the blob name?* if blob 1column is in the query then you are both name and blob even if you don't use it
Comment: `Have you ever had a cursor tell you that it has data` It's not your case: `a CursorWindow which has 0 rows` tells you that your Cursor is **empty**.
Comment: So you're saying that the blob is too big?  Would that cause the app crash when trying to even read the string which contains the blob name?
Answer: Thank you all for the help.
Turns out the cursor window does indeed not allow data greater than 1 MB in a query.
Bellow is the code that now pulls out the file in bits and pieces.
private byte[] ProcessRawData(String searchID) {
    String selection = TempImageEntry.ID + "=" + searchID;
    String [] cols;
    int count = 0;
    byte [] rawData = new byte[0];
    Long tracker = BlobSize;//use a generic length function of your choice
    do {
        cols = new String [] {"substr(" + TempImageEntry.RawData + ","+(1 + 1000000L * count)+",1000000)"};
        Cursor cursor = mDatabase.getReadableDatabase().query(TempImageEntry.TABLE_NAME,cols,selection,null,null,null,null);
        if(!cursor.moveToFirst())
        {
            cursor.close();
            Log.e(LOG_TAG,"Serious Error");
            return rawData;
        }
        byte [] theBit = cursor.getBlob(0);//get the current chunk
        cursor.close();
        byte[] c = new byte[rawData.length + theBit.length];//make room for the new chunk
        System.arraycopy(rawData, 0, c, 0, rawData.length);//copy old chunk into the new room
        System.arraycopy(theBit, 0, c, rawData.length, theBit.length);//copy the new chunk into the room made for the total
        rawData = c;//set the new collected as the main
        count++;
        tracker -= 1000000L;
    }while (tracker> 1000000L);
    cols = new String[]{"substr(" + TempImageEntry.RawData + "," + (1 + 1000000L * count) + "," + tracker + ")"};
    Cursor cursor = mDatabase.getReadableDatabase().query(TempImageEntry.TABLE_NAME, cols, selection, null, null, null, null);
    if (!cursor.moveToFirst()) {
        cursor.close();
        Log.e(LOG_TAG, "Serious Error");
        return rawData;
    }
    byte[] theBit = cursor.getBlob(0);
    cursor.close();
    byte[] c = new byte[rawData.length + theBit.length];
    System.arraycopy(rawData, 0, c, 0, rawData.length);
    System.arraycopy(theBit, 0, c, rawData.length, theBit.length);
    rawData = c;

    return rawData;
}

Maybe no the best way of doing this but it's functional.
Yes storing blobs is maybe not the best way of doing this since we can write to disk but I've experienced problems with android with files going missing and we want to explicitly destroy files when they are no longer needed.


very slow convergence of Picard method for solving nonlinear system of equations

Question: I have a nonlinear system of equations as
$$
\left(\mathbf{K}_{\mathbf{L}}+\mathbf{K}_{\mathbf{N L}}(\mathbf{X})\right) \mathbf{X}=\mathbf{F}
$$
in which $\mathbf{K}_{\mathbf{N L}}(\mathbf{X})$ represents the nonlinear stiffness matrix which is dependent to $\mathbf{X}$.
I'm solving with Picard iteration like this:

first ignore the nonlinear stiffness matrix and solve the linear
matrix for $\mathbf{X}$.
put the resulting $\mathbf{X}$ in the nonlinear stiffness matrix and solve the full equation for $\mathbf{X}$.
check convergence and repeat 2 if the convergence is not satisfied.

the problem i have here is when the force vector($\mathbf{F}$) is small the nonlinear equation solves very fast but when i increase the force beyond some threshold it gets ages to converge.
i have tried to solve it using Matlab fsolve function with algorithms like 'trust-region' and 'levenberg-marquardt' but the same thing happens with large force vectors.
is there any way i can improve the convergence speed ?
p.s.
heres a gif of the result vector $\mathbf{X}$ inside the convergence loop with a force vector slighly over the threshold.

edit(more details):
so my problem is bending of a nonlinear timoshenko beam that has three governing equations as below:
$$
-\frac{d}{d x}\left\{A_{x x}\left[\frac{d u}{d x}+\frac{1}{2}\left(\frac{d w}{d x}\right)^{2}\right]+B_{x x} \frac{d \phi_{x}}{d x}\right\}=0
$$
$$
-\frac{d}{d x}\left\{A_{x x} \frac{d w}{d x}\left[\frac{d u}{d x}+\frac{1}{2}\left(\frac{d w}{d x}\right)^{2}\right]+B_{x x} \frac{d w}{d x} \frac{d \phi_{x}}{d x}\right\}-\frac{d}{d x}\left[S_{x x}\left(\frac{d w}{d x}+\phi_{x}\right)\right]=q
$$
$$
-\frac{d}{d x}\left\{D_{x x} \frac{d \phi_{x}}{d x}+B_{x x}\left[\frac{d u}{d x}+\frac{1}{2}\left(\frac{d w}{d x}\right)^{2}\right]\right\}+S_{x x}\left(\frac{d w}{d x}+\phi_{x}\right)=0
$$
along with the proper boundary conditions and using finite difference, when assembled they form:
$$
\left(\mathbf{K}_{\mathbf{L}}+\mathbf{K}_{\mathbf{N L}}(\mathbf{X})\right) \mathbf{X}=\mathbf{F}
$$
Comment: The ordinary Picard algorithm converges linearly (notice that the scheme revolves around a fixed point iteration). So, it is not "superfast" even if you are close to the solution, this can be a nightmare (or a night with eyes open until the end of computation) for some large systems. Still, you may want to check if conditions for using the scheme hold, i.e. the function and its derivative are continuous at the point where you start your iterations (typically the origin).
Comment: This approach is reasonable only if $\mathbf K_{NL} \ll \mathbf K_L$. Otherwise you should use linearization of $\mathbf K_{NL}$ either full (Newton's method) or partial. The less is the nonlinear term, the faster the convergence will be.
Comment: Have you tried `ode23s` and others?
Comment: @user10354138 whats the difference between `fsolve` and `ode23s` ?
Comment: the function is continuous but i didn't really consider the derivative. do you mean the derivative with respect to time or `X` itself? because X is has three separate variables`{u;w;s}`
Comment: Your numerical question sounds like a conditioning issue. The solver of ode23s might resolve the issue since they're designed for solving "stiff" problems. I've got a few questoins: 1) What do you mean by a *nonlinear matrix*? and 2) Also, what is the error tolerance your solver is using? Lowering your error tolerance may yield faster "convergence"
Comment: thanks for your suggestion @Zim i edited my question to answer your first question. about your second question i don't think lowering the error tolerance is gonna fix it because it is obvious from the gif i provided that the solution is not converging and it is oscillating with very big difference.
i think @uranix is right because as i increase the force, $\mathbf{K}_{\mathbf{N L}}\left(\mathbf{X}\right)$ gets bigger and the approach gets inefficient. but for the Newtons method i have used matlabs `fsolve` and from the documentations it uses Newtons methos,but the same happens.
Comment: It may help if you put more details in. Best, just let us know what $K_L$ and $K_{NL}(X)$ are. Right now the question is too general to offer anything better than wild shots (and, from what you are saying, it looks like they don't help much)
Comment: okay i will add more details to the post, thanks @fedja
Comment: Are $A,B,D,S$ constants and $u,w,\phi_x$- unknown functions? If so, one thing that strikes me is that your first equation allows one to eliminate $u$ and all non-linearity from the second two if we introduce the constant parameter $C=\{Axx[]+\dots\}$ and then to quickly solve the resulting linear system and solve for $u$ in the end (another linear equation), so it looks like you are down to a one-variable problem $H(C)=something$ where $H$ is obtained by solving a purely linear system and something, apparently, is determined by the boundary conditions. Am I missing anything?
Comment: @fedja yes you are right about the constants and unknown functions but i am not understanding your method for eliminating _u_ and the nonlinear parts. could you elaborate on that some more? thank you
Comment: According to the first equation, the full expression in braces is constant. Denote that constant by $C$. Then, $\frac{du}{dx}+\frac 12(\frac{dw}{dx})^2=(C-B_{xx}\frac {d\phi_x}{dx})/A_{xx}$. Now plug this into the second and the third equations and treat $C$ as a known parameter. You'll get two *linear* ODE's for $w$ and $\psi_x$ that you can solve as quickly as you can solve your linear systems in general. Now, when you have your $w$ and $\phi_x$, you can solve the first equation for $u$ in no time. The result, will satisfy all 3 equations, so only the boundary conditions may be hurt. (contd)
Comment: What exactly are the boundary conditions, by the way? Can you post them too?
Comment: If none of these suggestions help you on thing that you can of course always do is throw more compute at it. In particular if you have access to a fast graphics card, GPU computing can provide pretty substantial gains for linear algebra problems. Also automatic differentiation libraries can help in providing accurate derivatives. You could try for example with pytorch's `torch.optim.LBFGS` optimizer.
Answer: Here's a simple idea you could try with very little extra effort: Your GIF shows that it's oscillating back and forth, a phenomenon that can also occur in classical gradient descent algorithms if the problem is bad conditioned. A very popular and powerful method to alleviate this kind of problem is called momentum, which basically consists of averaging over previous iterations.
So instead of throwing away all the previous iterates, you can do something like
$$ x_{k+1} = (1-\beta)g(x_{k}) + \beta x_k$$
Note that when $\beta=0$, we recover a standard fixed point iteration. Consider a simple fixed point problem like $x=\cos(x)$, which exhibits the oscillatory phenomenon. Then, starting from the same seed here are the residuals $|x_*-x_k|$ for different values of $\beta$:
$$
\small\begin{array}{lllllll}
 k  & \beta=0 & \beta=0.1 &\beta=0.2 &\beta=0.3 &\beta=0.4 &\beta=0.5
\\\hline 0 &    5.45787 &5.45787 &5.45787 &5.45787 &5.45787 &5.45787
\\1 &     0.2572 &    0.777267 &      1.29733 &       1.8174 &      2.33747 &      2.85754
\\2 &    0.19566 &    0.538475 &     0.690985 &     0.555697 &     0.107195 &     0.610102 \\3 &   0.116858 &    0.162927 &    0.0696096 &   0.00419339 &   0.00218156 &    0.0454083 \\4 &  0.0835784 &   0.0908543 &    0.0249916 &  0.000723828 &   8.0351e-06 &    0.0070347 \\5 &   0.053654 &   0.0431759 &   0.00828335 &  0.000124022 &  3.34983e-08 &    0.0011389 \\6 &  0.0371882 &   0.0224696 &   0.00282738 &  2.12772e-05 &  1.39595e-10 &  0.000185622 \\7 &  0.0245336 &   0.0112062 &  0.000955803 &  3.64953e-06 &  5.81757e-13 &  3.02859e-05 \\8 &  0.0167469 &  0.00571477 &  0.000324182 &  6.26001e-07 &  2.44249e-15 &  4.94232e-06 \\9 &  0.0111768 &  0.00288222 &  0.000109831 &  1.07377e-07 &  1.11022e-16 &  8.06552e-07 \end{array}
$$
A well chosen momentum can speed up convergence tremendously! A variant of this idea specific to fixed point iterations appears to be known as Anderson Acceleration.
Comment: I like the proposal, but although I cannot confirm it from the information in the question as posed  by @omgtheykilledkenny, it seems that those oscillations are the result of plotting the solution for the linear stiffness and the update considering the nonlinear part. If using damping factors, it may be necessary to consider dissipation in some problems (physical systems may not conserve energy under some of these schemes).
Comment: Thank you for your proposal @Hyperplane. i am going to try this method and will let you know how it works. if i got it correctly the function `g(x)` gives the result of my system of nonlinear equations, right?
Comment: Isn't $g(x_k)$ supposed to be $x_{k-1}$? Otherwise you are just using the previous iterate.
Comment: @Mick $g$ returns the solution to the linear system with stiffness matrix evaluated at $x_k$, i.e. $g(x_k) = \text{solve}(K_L+K_{NL}(x_k),\, F)$
Answer: I assume that $K_{NL}(0) = 0$.
Currently you are using the iteration
$$
(K_L + K_{NL}(X_n))X_{n+1} = F
$$
with $X_0 = 0$. Instead, first solve
$$
(K_L + K_{NL}(X_\sigma))X_\sigma = \sigma F
$$
for small $\sigma$, using this method. This converges quickly as you noticed. Then  solve
$$
(K_L + K_{NL}(X_{\sigma'}))X_{\sigma'} = \sigma' F
$$
with the same iteration for some $\sigma' > \sigma$, using the same iteration but now starting with the previously found $X_\sigma$ and not with the zero vector. And so on until the right hand side is $F$.
For example, choose $\sigma = N^{-1}, \, \sigma' = 2 N^{-1}$ and so on, for sufficiently large $N$.
Of course Anderson acceleration  is also a good idea here :)
Comment: oh so you mean that i start solving the nonlinear equations for small forces and with their solution start increasing the force and converge for force? hummm seems like a reasonable idea. let me try that. i have read the Anderson acceleration papers but it looks so complicated however i trie the suggestion of @hyperplane but it gives different answers for different beta ratios.
Answer: You can try some of the convergence acceleration algorithms which can work very well for fixed-point (Picard-type) iterations.  If you are using R, there is a package called SQUAREM which implements a reliable, convergence acceleration scheme.  It is based on the paper (Varadhan and Roland, Simple and Globally Convergent Methods for Accelerating the Convergence of Any EM Algorithm, Scandinavian Journal of Statistics, 2008).  EM algorithms are essentially Picard-like algorithms - they are contraction mappings which converge slowly.


Diophantine equations solved using algebraic numbers?

Question: On Mathworld it says some diophantine equations can be solved using algebraic numbers. I know one example which is factor $x^2 + y^2$ in $\mathbb{Z}[\sqrt{-1}]$ to find the Pythagorean triples.
I would be very interested in finding some examples of harder equations (not quadratic) which are also solved easily using algebraic numbers. Thank you!
Comment: I haven't seen Section 7 of Lenstra's article mentioned: http://www.math.leidenuniv.nl/~psh/ANTproc/01lenstra.pdf
Answer: Perhaps the simplest example is the parametrization of primitive Pythagorean triples $ z^2 = x^2 + y^2 = (x-y\,i)(x+y\,i).\,$ The key idea behind the proof is this: $\ x-y\,i,\ x+y\,i\ $ are coprime factors of a square in a UFD, hence they must themselves be squares (up to unit factors). So $\ x + y\, i = (m + n\ i)^2 =\ m^2 - n^2 + 2mn\, i,\,$ which is the well-known parametrization.
Similarly we can solve low degree cases of Fermat's Last Theorem by employing analogous factorizations over certain rings of algebraic integers. For example, Gauss showed there are no solutions for exponent 3 by working in the ring of integers of $\ \mathbb Q(\sqrt{-3}),\,$ and Dirichlet did similarly for exponent 5 using $\ \mathbb Q(\sqrt{5})\,.$ Later Kummer generalized these techniques to handle all regular prime exponents by working over rings of cyclotomic integers. For a nice exposition see Ribenboim: 13 lectures on Fermat's last theorem. Weil nicely summarizes the essence of these techniques in his Number Theory, Ch.IV,S.VI,p.335:
Comment: For the integer case of coprime divisors of powers, see [this answer](http://math.stackexchange.com/a/822012/242) for a proof by induction, and see [this answer](http://math.stackexchange.com/a/21637/242) for a proof via gcds.
Answer: The classic example is certain Mordell curves.  I can never quite remember which ones have this property off the top of my head, but for example I think $y^2 = x^3 - 1$ is one of them.  (Write it as $y^2 + 1 = x^3$ and factor the LHS in $\mathbb{Z}[i]$.)  There might be a list in some books on Diophantine equations and/or algebraic number theory and/or elliptic curves.
There is also the regular case of Fermat's last theorem.  I don't know if this counts as "easy," though.
Comment: For some worked examples of Mordell's equation, using algebraic numbers, see Section 3 of http://www.math.uconn.edu/~kconrad/blurbs/gradnumthy/mordelleqn1.pdf
Answer: Euler famously used algebraic integers to solve diophantine problems, though not always exactly right.
For example, in article 182 of Chapter XII, Part II, of his Elements of Algebra (p. 396 in my brand new Cambridge Library Collection edition), he writes:

Let, therefore, the formula $x^2+cy^2$ be proposed, and let it be required to make it a square. As it is composed of the factors $(x+y\sqrt{-c})(x-y\sqrt{-c})$, these factors must either be squares, or squares multiplied by the same number. For, if the product of two numbers, for example, $pq$, must be a square, we must have $p=r^2$ and $q=s^2$; that is to say, each factor is of itself a square; or $p=mr^2$ and $q=ms^2$; and therefore these factors are squares multiplied by the same number. For which reason, let us make $x+y\sqrt{-c} = m(p+q\sqrt{-c})^2$; it will follow that $x-y\sqrt{-c} = m(p-q\sqrt{-c})^2$, and we shall have $x^2+cy^2 = m^2(p^2+cq^2)^2$, which is a square. Farther, in order to determine $x$ and $y$, we have the equations $x+y\sqrt{-c} = mp^2 + 2mpq\sqrt{-c} -mcq^2$, and $x-y\sqrt{-c} = mp^2-2mpq\sqrt{-c} - mcq^2$; in which $x$ is necessarily equal to the rational part, and $y\sqrt{-c}$ to the irrational part; so that $x=mp^2 - mcq^2$ and $y\sqrt{-c} = 2mpq\sqrt{-c}$, or $y=2mpq$; and these are the values of $x$ and $y$ that will transform the expression $x^2+cy^2$ into a square, $m^2(p^2+cq^2)^2$, the root of which is $mp^2+mcq^2$.

(Note that Euler in fact finds sufficient conditions, but not necessary ones, here, and there is an implicit assumption of unique factorization). In Article 187, he proceeds along the same lines to discuss when $ax^2+cy^2$ will be a cube, working with the factorization $ax^2+cy^2 = (x\sqrt{a}+y\sqrt{-c})(x\sqrt{a} - y\sqrt{-c})$.
Euler himself knew this did not quite work out in general: in Article 195 he discusses when $2x^2-5$ is a cube; his method yields the answer that it is never a cube, but yet he notes that $x=4$ gives $2x^2 - 5 = 27 = 3^3$; his "investigation" into the failure involves some rather strenuous hand-waving, concluding that the problem is that we have a difference instead of a sum as before.
Answer: An interesting example which appears in section $4.9$ of Stewart and Tall's Algebraic Number Theory and Fermat's Last Theorem is the solution of the Ramanujan-Nagell equation given by
$$x^2 + 7 = 2^n$$
The idea is to work over the quadratic field $\mathbb{Q}(\sqrt{-7})$ and use the fact that it has unique factorization in order to compare two factorizations at the core of the argument.
The argument needs to take care of different cases separately and does not run as "smoothly" as the arguments in some of the examples mentioned in the other answers, but that's probably in some sense due to the fact that this equation involves an exponential, which only makes the already difficult problem of solving a Diophantine equation worse.
Answer: Fermat's Last Theorem was originally "proved" by using some elementary arguments and the "fact" that the ring of integers of $\mathbb{Q}(\zeta_p)$ is a UFD (which it is not), where $\zeta_p$ is a primitive $p$th root of unity. These arguments do hold when $\mathcal{O}_p$ is a UFD though; for a thorough account of the argument, see Chapter 1 of Marcus's Number Fields.
Answer: There are many examples, some of which I see you have already gotten :-)
Here is one example I had come across recently:

Show that the following diophantine equation,
  for integral $\displaystyle a,b$, has no non-trivial solutions.
$$3b^4 + 3b^2 + 1 = a^2$$

I came across this while trying to find an "elementary" solution to the diophantine equation
$$y^2 = x^3 - 1$$
which is easily solved using $\displaystyle \mathbb{Z}[i]$, see this here: Integral solutions to $y^{2}=x^{3}-1$
Of course, there might be an easy elementary proof for $\displaystyle 3b^4 + 3b^2 + 1 = a^2$, but, in fact this is closely related to the Pell's equation $\displaystyle 3x^2 + 1 = y^2$ and amounts to showing that the non-trivial odd values of $\displaystyle x$ are such that $\displaystyle \frac{x-1}{2}$ cannot be a perfect square. This itself can be cast into a problem of the terms of a linear recurrence never being perfect squares. So I do expect this problem to give some resistance to an elementary solution.
To solve the problem:
Mutiply by $\displaystyle 9b^2$
$$3b^2(9b^4 + 9b^2 + 3) = (3ab)^2$$
put $\displaystyle x = 3b^2 + 1$ and $\displaystyle y = 3ab$
$$(x-1)(x^2 +x + 1) = y^2$$
$$x^3 - 1 = y^2$$
which we can show has no non-trivial solutions easily, by using $\displaystyle \mathbb{Z}[i]$.
Note: If one can prove non-existence of $\displaystyle 3b^4 + 3b^2 + 1 = a^2$ by other means, we will have found a different proof of non-existence of $\displaystyle x^3 - 1= y^2$, because the existence of non-trivial solutions to $\displaystyle x^3 - 1= y^2$ implies the existence of non-trivial solutions to $\displaystyle 3b^4 + 3b^2 + 1 = a^2$. (That is how I came across this).
I will leave that to you.
Comment: Does this mean an elementary treatment of $y^2 = x^3-1$ should be called a Moronic approach?
Comment: @KCd: Only if it works :-P


What is army count of commander in Warzone?

Question: What is army count of commander in Warzone and how much army strength is needed to kill him?
Answer: A commander is worth 7 armies.
Thus he kills 4 while attacking in a normal game and needs to be attacked by 11 to be killed. If you commander is killed, You lose, and all of you territories become neutral.


Rewrite a JSON array in PHP so that jQuery can read it?

Question: I'm trying to create a JSON array in PHP that jQuery can use and access but for some reason It doesn't work. I get no error messages on  the client side nor in the server logs and if I access enc.php directly, it does work, but I'm not sure if the output is correct (the array format).

What I want:
I would like to access the data with jQuery using data[i][0] for the ID ([i] because it's in a loop), and data[i][1] for the message and so on.
Maybe I'm trying to do this the wrong way, if so please help me by pointing me in the right direction or provide an example.
My code:
The current PHP code:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
  $fetchedid = $row['id'];
  $fetchedkey = $row['chat_key'];
  $fetchednonce = $row['chat_nonce'];
  $fetcheduser = $row['chat_user'];
  $fetchedmsg = $row['chat_msg'];

  $plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
  $out = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
  header('Content-Type: application/json');
  ob_end_clean();
  echo json_encode($out);
}

Result:
{"id":297,"msg":"test message","user":"john"}

My jQuery (Ajax) code:
$.ajax({
   type: "GET",
   url: "enc.php",
   dataType: "json",
   success: function(data) {
     console.log('Update success called');
     if (data == 2) {
       // No messages to fetch
     } else if (data == 3) {
       // Cookie Tampering detected
     } else if (data == 5) {
       $("#chat").remove();
       alert("Den här chatten är stängd (tiden har gått ut).");
       window.location.href = "/?logout=safe";
     }
     else {
     for (i = 0; i < data.length; ++i) {
       var mid = data[i][0];
       $.cookie("cmid", mid);
       var from = data[i][1];
       var msg = data[i][2];
       $("#chat").append('

@'+from+'

'+msg+'

');
     }
     $('textarea').focus();
     $(".chat_area").animate({ scrollTop: $(".chat_area")[0].scrollHeight}, 1000);
 }
}
});

Answer: You can access object using . notation. To access values use key. for example to access id use data.id. If you have object you can't loop using length.
           var mid = data.id; //specify key to access id
           $.cookie("cmid", mid);
           var from = data.user;
           var msg = data.msg;
           $("#chat").append('

@'+from+'

'+msg+'

');

Answer: The issue is you are outputting individual JSON strings in your while loop which is not correct because the combined output is invalid JSON. The solution is to build an array and then output the array at the end.
$arr = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
  $fetchedid = $row['id'];
  $fetchedkey = $row['chat_key'];
  $fetchednonce = $row['chat_nonce'];
  $fetcheduser = $row['chat_user'];
  $fetchedmsg = $row['chat_msg'];

  $plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
  $out = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);

  $arr[] = $out;
}

header('Content-Type: application/json');
ob_end_clean();
echo json_encode($arr); // encode the final array

Now, your output can contain multiple chat messages and is valid JSON, such as:
[{"id":297,"msg":"test message","user":"john"}, {"id":300,"msg2":"test2 message","user":"john"}]

In the JavaScript, refer to the property names instead of [0], [1] etc:
var mid = data[i].id;
$.cookie("cmid", mid);
var from = data[i].user;
var msg = data[i].message;

Answer: the problem stems from the fact that your result is not the json for an array of objects but a simple object, so the line
 for (i = 0; i < data.length; ++i) {

never iterates as data does not have a length. you want your result to look like
Result :
[
    {"id":297,"msg":"test message","user":"john"}
]

that way it will also hold more than one john ;)
suggestion
so I believe your php should be :
$result = $stmt->get_result();
$out = array();
while ($row = $result->fetch_assoc()) {
    //... your code doesn't change here

    $plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
    //here we append to $out
    $out[] = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
    header('Content-Type: application/json');
    ob_end_clean();
    //echo json_encode($out);// not yet...
}
echo json_encode($out);//but now!

Comment: Thank you! with the code you provided I got a reply from jQuery, how ever, it says that the data is undefined? Do i need to change my jQuery code aswel?
Comment: I wouldn' expect it, no. try to call `console.log(data)` to see what comes back (or go to the Network tab of your browser's dev tools) ?
Comment: Ignore that. This does indeed work for my situation, only thing to note is that I had to change data[i][0] to data[i].id  ! The reason why I choose your answer is because this suits my situation and it allows me to continue to use for (i = 0; i < data.length; ++i)
Comment: Ok thanks! I had missed these `data[i][0]` calls. Happy it works!


Disabling(Removing) root completely!

Question: This might seem like a crazy step, but..
How to disable(remove) root completely from a system? (I'm currently working on Ubuntu 18.04).
I'm working to modify an OS so that no user would ever be able to mess up with the internal files... the user need to have very limited control over the system. This can be done by giving sudo access to only limited commands to the users and taking off any other way to access sudo or su... This question is just my crazy thought that if the root is completely disabled there can be no way some one can figure out a way to abuse the system.. just trying to know if there is a possibility to work this way.
I understand that is creates obvious issues, but is there a way to work around them?
Thanks :)
Comment: The answer is nope. Why would you even consider "removing root" as a possibility and what do you think you could achieve by that? It sounds like you have an [XY problem](https://meta.stackexchange.com/q/66377/280883) here. Please explain what your actual goal is.
Comment: root is disabled by default with Ubuntu, so you need do nothing.  It's not removed though, just disabled.
Comment: they need `sudo` access to achieve it (enabling root), or access to the physical machine (where on it is moot, as they can boot a live and bypass OS security anyway unless you've built in higher security than just disabling root).  Don't give them `sudo` access, otherwise you're wasting your time if they already have physical access to hardware
Comment: We had a similar question yesterday: https://askubuntu.com/questions/1167352/create-a-system-with-no-root
Comment: Also take a look at this page about sudo and root in Ubuntu: https://help.ubuntu.com/community/RootSudo
Comment: Even if it were possible the amount of time would be extraordinary and you would end up with a "Frankenstein" system nobody could or would support.
Comment: What do mean by 'root'?  The root partition where all the nice things are kept, or the nuisance of typing your root password everytime you want to change something(you want to be god of your system all the time), or do you want to prevent you or someone from changing the system by using root password.
Comment: There is not. Why do you want to this? There may be another way to achieve the effect you're looking for.
Comment: Please explain what you are trying to accomplish by removing root.
Comment: @mchid  I'm working to modify an OS so that no user would ever be able to mess up with the internal files... the user need to have very limited control over the system. This can be done by giving sudo access to only limited commands to the users and taking off any other way to access sudo or su... This question is just my crazy thought that if the root is completely disabled there can be no way some one can figure out a way to abuse the system.. just trying to know if there is a possibility to work this way.
Comment: @guiverc yes, the root is 'locked' by default in ubuntu, but anyone with some basic research can work around it to create a new password to root and activate it..
Comment: @Byte Commander, I hope that the above comments can give you an clarification
Comment: @frankenstein This is not exactly the same but you might find this question interesting: https://unix.stackexchange.com/questions/390135/can-i-create-a-super-super-user-so-that-i-can-actually-have-a-user-that-can-de
Comment: @frankenstein One thing: you can prevent users from accessing "single user mode" in grub by setting the grub font color and the grub background colors to the same value so that the grub prompt cannot be seen. Additionally, you can usually lock down the BIOS and the boot menu so that the system cannot be accessed through a USB or CD.
Answer: If there is no root password set, login as root is disabled. This is typically the default configuration of Ubuntu when you install it and set up a user password.
That said, it sounds like you are asking this from a security perspective so I'll mention a couple of things. Firstly, if a user has physical access to the machine they can get root access via a number of means such as replacing the boot drive, booting from something else. Full disk encryption can make it impossible for this person with physical access to see your data but not to wipe it.
Secondly, disabling the mechanism to log in as root doesn't really provide notable security over having a non-guessable passphrase, and just not giving that passphrase to others.
Thirdly, you mention giving sudo access to users. Done incorrectly this can inadvertently open up the ability for users to do much more than you intend for them to. If you have a locked down system it's not typical to let users do anything that requires superuser access.

Disabling(Removing) root completely!


Why I am getting windows security alert in IE but not Chrome?

Question: I am getting this security alert popup when using IE but not chrome. Did anyone experience this issue and were you able to resolve it?
Comment: What security alert?
Comment: When you ask completely indecipherable, incomplete questions like this you're going to risk an automatic question ban.
Answer: the security pop up is related to the Load Balancer timing out. In Chrome, the popup is not showing but at the background it is throwing an error. So the fix is to increase the Load Balancer so that the tcp connection stays alive until it times out at the backend.


Will Ubuntu 12.04 run smoothly with these specs?

Question:
Possible Duplicate:
What are the minimum system requirements for 12.04 LTS?

I have a computer with the following specs:
Intel Pentium 4 3.00 GHz
2 GB RAM
a PCI Nvidia video card

Will Ubuntu run smoothly on this machine?
Answer: Yes, it will. You can check specifications here.
Answer: Ubuntu should run smoothly on this machine, but you might have to use Unity 2D rather than regular (3D) Unity for the graphical user interface. This might be selected for you, but if the interface malfunctions or is slow, then click the Ubuntu logo on the login screen and select Ubuntu 2D (instead of Ubuntu). Please note that this is a per-user setting.
This is assuming your NVidia card is PCI, rather than PCI Express. Any NVidia card for PCI Express should be sufficient to the task of running 3D Unity, though it's possibly you'll need to install the proprietary drivers (using the Additional Drivers utility) to get that to work.
If you want more detailed information, you'll need to tell us the specific model of PCI NVidia graphics card you have. It would also be useful if you told us the exact make and model of your computer or, if that is inapplicable, the make and model of your motherboard.
As Luka has pointed out, you can always check the system requirements for Ubuntu and its official derivatives.


Program to compare two files line by line

Question: Is there a GUI-based program on Ubuntu that compares two files line by line and indicates where two lines do not match? If not, any console app that does the same thing?
Answer:
meld
tkdiff
vim

meld is -my- favorite.
Console has a command for it:
diff {file1} {file2}
Comment: Wow!  Meld is now also my favourite!


dojo drag n drop (DND) not working

Question: I have dojo tree and a list of items that can be added to the tree.  Would like to use dojo dnd (drag n drop) so that items in the list can be dragged onto the tree to add them.
Here is an example of what I'm trying to do:
jsfiddle example
When you mouse-down on a unassigned list item and drag it onto the tree, nothing appears to happen, but if you look at the web browser console, you can see that it always complains about TypeError: a is undefined in dojo's Memory.js module.
I am trying to do something similar to this example Dojo drag-n-drop example.  In this example, grab an item from the items list and drag it onto the tree on the right (Collection tree).
I am using dojo 1.10.4 and also new to using trees and drag-n-drop (dojo dnd).  What am I missing here to be able to drag-n-drop from the list onto the tree??
Answer: I used Dojo Tree on the left of the screen and Dragula (https://github.com/bevacqua/dragula) for the list on the right. It is very simple and it works.
Here there is the list object example with Dragula.
this.dnd = dragula([this.list], {
       isContainer: function (el) {
         return el.classList.contains('dijitTreeRow');
       }
     });
     this.dnd.on('shadow', function (el, container, source) {         // the event when yoi drag something tipo hover
     //   console.log(el, container);
       var oldContainer;                                         // change color of the drop item
       oldContainer = query('.dndHover')[0];
       if (oldContainer) {
         domClass.remove(oldContainer, 'dndHover');
       }
       if (container === source) {                               // if drag and drop on the list do nothing
         return;
       }
       domClass.add(container, 'dndHover');                  // highlight current node
     });

     this.dnd.on('drop', function (el, container, source) {           // drop event
        var oldContainer;                                         // remove highlight
        oldContainer = query('.dndHover')[0];
        if (oldContainer) {
           domClass.remove(oldContainer, 'dndHover');
        }
        if (container !== source) {
           // var widget = registry.getEnclosingWidget(el);
           var target = registry.getEnclosingWidget(container);
           // console.log(el, target);

           // target = TREE NODE
           // make your action (query, etc..)

        }
     }.bind(this));

CSS:
.dndHover{
   background-color: #52D017 !important;
}

.dijitTreeRow .dragdiv {
   display: none;
}

Comment: I will give this a try Stefano..Thx!!

dojo drag n drop (DND) not working


Can I use dispatch group not in a loop?

Question: Say I have 3 different asynchronous tasks I want to get done before calling some function. I'm aware of using dispatch groups to do such a thing if those tasks were in a loop,
    var dispatchGroup = DispatchGroup()

    for task in tasks {
        dispatchGroup.enter()

        DoSomeTask { (error, ref) -> Void in
            dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: DispatchQueue.main, execute: {
        DoSomeFunction()
    })

However, I'm confused on how you'd do this if those tasks were all in the same function but didn't have to do with eachother, like pushing 3 different values to your database. Something like this:
   updateDatabase() {
        var dispatchGroup = DispatchGroup()

        DoTask1 { (error, ref) -> Void in
        }

        DoTask2 { (error, ref) -> Void in
        }

        DoTask3 { (error, ref) -> Void in
        }
   }

Where would you put the leave and enter statement in such a case as this?
Answer: In this case your updateDatabase() function needs a completion block that you call after all update are done:
updateDatabase(onSccess completion:() -> Void) {
    var dispatchGroup = DispatchGroup()

    dispatchGroup.enter()
    DoTask1 { (error, ref) -> Void in
        dispatchGroup.leave()
    }

    dispatchGroup.enter()
    DoTask2 { (error, ref) -> Void in
        dispatchGroup.leave()
    }

    dispatchGroup.enter()
    DoTask3 { (error, ref) -> Void in
        dispatchGroup.leave()
    }

    dispatchGroup.notify(queue: DispatchQueue.main) {
        completion()
    }
}

You than call it like this:
updateDatabase() {
    //do somthing after updating
}

Can I use dispatch group not in a loop?


What is this function on ordinals called?

Question: Define a function $f:\mathbf{ON}\to\mathbf{ON}$ as follows: for each ordinal number $\alpha$ let $$f(\alpha)=\operatorname{ord(}\lbrace \beta<\alpha|\text{ }\beta\textrm{ is a limit ordinal}\rbrace).$$ This function seems useful, as it seems to describe in some sense "how many levels" an ordinal number has, which leads me to think it might have been studied before. Is there some standard name/notation for this function?
Comment: @rschwieb: You're correct that we cannot define class functions in ZFC in the sense that a class function is not a *set* of ordered pairs. However, there is usually an easy way to circumvent this. E.g. we can work with restrictions of the function $F$ to subsets of the class of all ordinals. Or instead of calling this a function we try to write down a formula $P(x,y)$ show that for each ordinal $\alpha$ there exists unique ordinal $\beta$ such that $P(\alpha,\beta)$. I guess such consideration are usually omitted in textbooks, since they would make things look complicated and (continued)
Comment: (continued) it is assumed that the reader is experienced enough to mend this by himself.
There was also some discussion about this at MSE:
[How do we justify functions on the Ordinals](http://math.stackexchange.com/questions/137319/how-do-we-justify-functions-on-the-ordinals) or  [class function question](http://math.stackexchange.com/questions/84486/class-function-question). One more ping for @Nils.
Comment: @Nils: Yes. So the language of ZFC can't express things like "there is a class with such and such properties". One thing it can do, given an explicit formula defining a class, is say "the class defined by this formula has such and such properties". This is often enough for what one wants to do. So for example ZF+V=L can't prove (or even say) "there's a definable well-ordering of the universe", but it can prove " defines a well-ordering of the universe".
Comment: You got me wondering if anything wonky can happen if you define a function with a domain which is a proper class... Is that set-theoretically kosher?
Comment: Since the limit ordinals are exactly the ordinals of the form $\omega \gamma$, this is more or less just (left) division by $\omega$.
Comment: @ChrisEagle: right, that does make sense. Is this standard, though? I'm not sure I've seen division of ordinals defined in Jech's Set Theory, for example.
Comment: I don't know how standard ordinal division is. It was in the course and book from which I first learnt about ordinals, and is described in the wikipedia article on [ordinal arithmetic](http://en.wikipedia.org/wiki/Ordinal_arithmetic).
Comment: @rschwieb: I second you. At least in ZFC functions between proper classes don't make sense, because to my knowledge we cannot even make precise the notion of a proper class using ZFC only.
Comment: @Martin Sleziak: Above all, thanks for the links. I have yet to study them in detail. But I'd like to get one thing straight so I just state it as something I think is true, and I would really appreciate any criticism: Inside any model of ZF, using ZF alone, you cannot define what a proper class is. You need some meta-language to actually talk about it.
Comment: @Nils: I think that there are people at this site that are much more competent to answer your question from the last comment than me; but I think you're correct; at least for the reason that in the language of ZF every object is a set, so we cannot speak about classes at all.
Comment: @Martin,Chris: Thanks for your responses!
Answer: An ordinal $\alpha$ is a limit if and only if it can be written as a product $\alpha=\omega \gamma$ for some ordinal $\gamma$. Thus your function $f$ is almost the same thing as division by $\omega$ (ignoring the remainder).
In detail: for any ordinals $\alpha$, $\beta$, with $\beta>0$, there exists a unique pair of ordinals $\gamma$, $\delta$ such that $\alpha=\beta \gamma + \delta$ and $\delta <\beta$. As in the finite case, we call this division by $\beta$, and call $\gamma$ the quotient and $\delta$ the remainder. If the remainder on dividing $\alpha$ by $\omega$ is $0$, then $f(\alpha)$ is the same as the quotient. If the remainder is nonzero, then $f(\alpha)$ is the quotient plus one.
The above assumes that zero is a limit ordinal. If not, then $f(\alpha)$ will be one smaller whenever it is finite and nonzero.


Is there a "right" answer to Quick Time Events?

Question: Every so often, there will be Quick Time Events (QTEs) that will occur and require an answer to be selected. These QTEs will have either three or four answers, depending on the situation, and different dialogs will take place based on the answer.
One instance is when you are touring Lestalum with Iris and QTEs are shown a few times. Every time I selected an answer, Noctis gained anywhere between 250 - 500 XP. Another instance was when you are heading towards the meteor and there was a QTE for deciding who was driving. I selected an answer and Ignis gained 500 XP.
Since different answers appear to give different characters XP, is there an overall "right" answer to these QTEs?
Answer: Depends on what you mean by "right".
If you mean "most rewards," then yes, there are right answers to these dialogues.
From this site:

During the story and on your journey, there will be conversations that require you to select an answer from multiple responses. How the conversation plays out and the contents of the parameters you obtain will change based on your response.

I've noticed that when I make choices that are favorable to the people I'm talking to, I get a pretty good amount of experience.
Here is another site that mentions different rewards for dialogue choices:

Some other things that you can do for instant APs in Final Fantasy are going into combat training, finishing a quest, performing combat challenges and doing beneficial dialogues choices.
Comment: I used right loosely (hence quotes) meaning it could go either way. Thanks for the swift response!
Comment: QTE in FF15 are a multifaceted thing. First they shape the character of the characters. Second, they are part of a reward system for opting "in" to giving the character a feel as presented or intended by the character designer. The down-side is that more often than not, its a conversation rail with an obviousness wherein you give a suboptimal answer, you get a suboptimal reward. However, in most cases, the QTE in FF15 is simply to make you engage with the party as a balance to the banter and back-chatter happening; it gives a degree of life to the overall game.


Highcharts chart width issue on lazy loading of stylesheet

Question: I am using Highcharts in an Angular 5 web application with https://github.com/cebor/angular-highcharts library. I am implementing themes in the app and for this purpose I am loading the stylesheet dynamically.
The issue is, when a chart is created it takes up the full width of the container which is fine. But the problem is that the stylesheet gets loaded into the memory late due to network delay. This causes the chart to overflow the container.
This is reproducible as here
https://stackblitz.com/edit/clarity-theme-switch-highchart-problem-1
Any help is appreciated!
Answer: When you load css you can add onload event handler. So only then show the chart:
<code>  this.linkRef.onload = () => this.showChart();
</code>
Here is your changed example:
https://stackblitz.com/edit/clarity-theme-switch-highchart-problem-1-wzqfaz?file=app%2Fapp.component.ts
Comment: Awesome answer. I was sure that I would have to hack my way out but this is just beautiful.


how to get all weeks of current month

Question: public static void getWeeksOfMonth(int month, int year) {
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    int ndays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    System.out.println(ndays + "<<<ff");
    int inc = 1;
    for (int i = 1; i <= ndays; i++) {
        String day = sdf.format(cal.getTime());
        System.out.println(day + "<<<");
        Log.e("quest", day + "<<<");
        inc++;
        if (i % 7 == 0) {
            Log.e("question", "=======week days===========");
            inc = 0;
        }
        if (inc >= 1 && i == ndays) {

            //cal.set(Calendar.MONTH, month+1);

            Log.e("endval", " " + day);
            for (int ii = inc; ii <= 6; ii++) {
                String dayi = sdf.format(cal.getTime());
                System.out.println(dayi + "<<<");
                Log.e("quest1", dayi + "<<<");
                inc++;
                if (ii % 7 == 0) {
                }
            }

        }
        cal.add(Calendar.DATE, 1);
    }

}

OutPut
Wednesday 01-Nov-2017<<<
Thursday 02-Nov-2017<<<
Friday 03-Nov-2017<<<
Saturday 04-Nov-2017<<<
Sunday 05-Nov-2017<<<
Monday 06-Nov-2017<<<
Tuesday 07-Nov-2017<<<
=======week days===========
Wednesday 08-Nov-2017<<<
Thursday 09-Nov-2017<<<
Friday 10-Nov-2017<<<
Saturday 11-Nov-2017<<<
Sunday 12-Nov-2017<<<
Monday 13-Nov-2017<<<
Tuesday 14-Nov-2017<<<
=======week days===========
Wednesday 15-Nov-2017<<<
Thursday 16-Nov-2017<<<
Friday 17-Nov-2017<<<
Saturday 18-Nov-2017<<<
Sunday 19-Nov-2017<<<
Monday 20-Nov-2017<<<
Tuesday 21-Nov-2017<<<
=======week days===========
Wednesday 22-Nov-2017<<<
Thursday 23-Nov-2017<<<
Friday 24-Nov-2017<<<
Saturday 25-Nov-2017<<<
Sunday 26-Nov-2017<<<
Monday 27-Nov-2017<<<
Tuesday 28-Nov-2017<<<
=======week days===========
Wednesday 29-Nov-2017<<<
Thursday 30-Nov-2017<<<
Thursday 30-Nov-2017<<<         Want Friday 1 dec 2017 and so on...
Thursday 30-Nov-2017<<<
Thursday 30-Nov-2017<<<
Thursday 30-Nov-2017<<<
Thursday 30-Nov-2017<<<
But I want to get all weeks(date 7 days of week) of current month
Pattern is like
Start with Friday of current month..
Friday 03-Nov-2017
Saturday 04-Nov-2017
Sunday 05-Nov-2017
Monday 06-Nov-2017
Tuesday 07-Nov-2017
Wednesday 08-Nov-2017
Thursday 09-Nov-2017
End with Thursday..
=======week days===========
Friday 10-Nov-2017
Saturday 11-Nov-2017
Sunday 12-Nov-2017
Monday 13-Nov-2017
Tuesday 14-Nov-2017
Wednesday 15-Nov-2017
Thursday 16-Nov-2017
=======week days===========
Friday 17-Nov-2017
Saturday 18-Nov-2017
Sunday 19-Nov-2017
Monday 20-Nov-2017
Tuesday 21-Nov-2017
Wednesday 22-Nov-2017
Thursday 23-Nov-2017
=======week days=========
Friday 24-Nov-2017
Saturday 25-Nov-2017
Sunday 26-Nov-2017
Monday 27-Nov-2017
Tuesday 28-Nov-2017
Wednesday 29-Nov-2017
Thursday 30-Nov-2017
=======week days===========
Friday 1-Dec-2017
Saturday 2-Dec-2017
Sunday 3-Dec-2017
Monday 4-Dec-2017
Tuesday 5-Dec-2017
Wednesday 6-Dec-2017
Thursday 7-Dec-2017
End with next month of first week, if current month last week have less then 7 days.
Comment: can you show us your code
Comment: @JohnJoe yes I update my question
Comment: [This](https://stackoverflow.com/a/12676277/4168607) may help .
Comment: @ADM Read my question I donot want number of weeks i want dates with weeks
Comment: I read it already . thats why i sent link for atleast some help.
Comment: See my updated post it will give your expected output
Comment: Even on Android I recommend you drop the long outdated classes `Date`, `SimpleDateFormat` and friends. [`java.time`, the modern Java date and time API also known as JSR-310](https://docs.oracle.com/javase/tutorial/datetime/), is so much nicer to work with. In general and even more so for special date requirements like yours. Yes, you can use it on Android through the [ThreeTanABP](https://github.com/JakeWharton/ThreeTenABP) project.
Answer: You have to use this code, I have to modify and add some lines. It will help you
 public static void getWeeksOfMonth(int month, int year) {
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(DAY_OF_MONTH, 1);
        int ndays = cal.getActualMaximum(DAY_OF_MONTH);
        System.out.println(ndays + "<<<ff");
        while (cal.get(DAY_OF_WEEK) != FRIDAY) {
            cal.add(DAY_OF_MONTH, 1);
            ndays--;
        }
        int remainingDays = ndays%7;
        if(remainingDays==0)
            ndays += 7;
        else
            ndays = ndays + 7 - remainingDays;

        int inc = 1;
        for (int i = 1; i <= ndays; i++) {
            String day = sdf.format(cal.getTime());
            System.out.println(day + "<<<");
            inc++;
            if (i % 7 == 0) {
                Log.e("question", "=======week days===========");
                inc = 0;
            }
            if (inc >= 1 && i == ndays) {
                for (int ii = inc; ii <= 6; ii++) {
                    String dayi = sdf.format(cal.getTime());
                    System.out.println(dayi + "<<<");
                    Log.e("quest1", dayi + "<<<");
                    inc++;
                }
            }
            cal.add(Calendar.DATE, 1);
        }

    }

My Output Is
Friday 03-Feb-2017<<<
Saturday 04-Feb-2017<<<
Sunday 05-Feb-2017<<<
Monday 06-Feb-2017<<<
Tuesday 07-Feb-2017<<<
Wednesday 08-Feb-2017<<<
Thursday 09-Feb-2017<<<
=====week days===========
Friday 10-Feb-2017<<<
Saturday 11-Feb-2017<<<
Sunday 12-Feb-2017<<<
Monday 13-Feb-2017<<<
Tuesday 14-Feb-2017<<<
Wednesday 15-Feb-2017<<<
Thursday 16-Feb-2017<<<
=====week days===========
Friday 17-Feb-2017<<<
Saturday 18-Feb-2017<<<
Sunday 19-Feb-2017<<<
Monday 20-Feb-2017<<<
Tuesday 21-Feb-2017<<<
Wednesday 22-Feb-2017<<<
Thursday 23-Feb-2017<<<
=====week days===========
Friday 24-Feb-2017<<<
Saturday 25-Feb-2017<<<
Sunday 26-Feb-2017<<<
Monday 27-Feb-2017<<<
Tuesday 28-Feb-2017<<<
Wednesday 01-Mar-2017<<<
Thursday 02-Mar-2017<<<
=====week days===========

Comment: That mean All month you are consider as first friday is a starting day?
Comment: good work
But only one promblem left i want to start day with FRIDAY and end with Thursday
Answer: Modify your for loop to this logic:
for(int i=1; i<=ndays;i+=7){

        String day = sdf.format(cal.getTime());
        System.out.println(day + "<<<");
        increment++;

        cal.add(Calendar.DATE, 1);
        if(increment >= 1){
            for(int j = 2;j <= 7;j++){
                String day1 = sdf.format(cal.getTime());
                System.out.println(day1 + "<<<");
                cal.add(Calendar.DATE, 1);
            }
            System.out.println("<<<END");
            increment = 0;
        }
    }

how to get all weeks of current month


Are the characteristic functions of bounded random variables infinite times continously derivatable (on the entire real line)?

Question: This question was raised to me, and I might need some help with this.
"If $X$ is bounded, meaning $\exists K$, that $|(X)| \le K$ than the characteristic function of $X$ can be derivated infinite times. "
First, I get that if the n-th moment exist, then the characteristic function can be derived n times. So i believe, that if all the moments exist (meaning they are not infinite), then the characteristic function can be derivated infinite times.
However, I can't prove that for a bounded distibution all moments exist. Wikipedia says that "For a distribution of mass or probability on a bounded intervall, the collection of all the moments (of all orders, from 0 to ∞) uniquely determines the distribution (Hausdorff moment problem)", but I cant see whether this means all the moments exist.
Thank you for your help!
Answer: if by your problem u mean K is a real number then X indeed has all finite moments and E(abs(X^n))<=K^n
Comment: Yes, thank you for the answer! My only question is why you used abs within E(x^n)?


What kind of integral is this, and how do you solve it?

Question: I have to solve this integral:

$\int_T(x^2+y^2)dx dy \ \ \ $ where $\ \ \ T=\{(x,y,z):x^2+y^2+z^2<1\}$

Now, what gets me confused is that i have to integrate only with respect to $x$ and $y$ but not $z$. The fact is that i have no idea on what this even means geometrically, is this a double integral on a 3d domain?
At first i didn't even noticed that and i managed to solve the integral (at least i believe) as if it was:

$\int_T(x^2+y^2)dx dy dz \ \ \ $ where $\ \ \ T=\{(x,y,z):x^2+y^2+z^2<1\}$

switching to spherical polar coordinates since $T$ represents a sphere of radius $1$:

$=\int_0^\pi d\theta\int_0^1 d\rho\int_0^{2\pi} \rho^2\sin^2(\theta)(\cos^2(\phi)+sin^2(\phi)) \ d\phi= \\
=\int_0^\pi d\theta\int_0^1 2\pi\rho^2\sin^2(\theta) \ d\rho= \\
=\int_0^\pi\frac{2}{3}\pi\sin^2(\theta) \ d\theta = \frac{\pi^2}{3}$

But the correct answer is $\frac{8\pi}{15}$ and i don't know how to get to that.
Comment: The most likely error is that you did polar coordinates transformation, which means the determinant of the jacobian is $\rho$. You should do spherical transformation instead (even if the $z$ does not appear) which should give you an additional term
Comment: Typo in the source material, perhaps?
Comment: @T.Bongers i don't believe, it is more plausible that i'm not understanding something since the exercise comes from a recent exam in my uni, anyway this is the copy/paste of the source material:  $\int_T(x^2+y^2)dxdy$ where $T=x^2+y^2+z^2<1$
Answer: The integral is indeed
$$\iiint (x^2+y^2) \, dxdydz$$
You made an error in computation. Note that $x^2+y^2$ is the distance to the $z$ axis, thus this can be thought of as the moment of inertia
$$I  =  \rho \iiint (x^2+y^2) \, dxdydz $$
where $\rho = \frac{M}{V}$ is the density of the sphere. But it is well known that
$$I = \frac{2}{5}MR^2 = \frac{2}{5}M$$
so, we are left with
$$\iiint (x^2+y^2) \, dxdydz = \frac{I}{\rho} = \frac{2}{5}\cdot\frac{4\pi}{3} = \frac{8\pi}{15}$$
I leave it to you to properly compute the integral, now that is clear you have made an error.


Json files losing indentation when using Beautify extension

Question: I have a JSON file that when I save on it using Beautify extension loses its format (indentation).
I use VS code editor.
If I disable Beautify, it works well and the indentation remains. Any suggestions on how to configure this are welcome.
All other files work well and are well indented when using Beautify.
Regards,
Alek
Answer: You can configure the beautify settings in the settings.json file.
For settings reference follow this link: https://github.com/HookyQR/VSCodeBeautify/blob/master/Settings.md
You can open the settings.json from the beautify extension page clicking on the settings button.
You can also try to use another extension called Prettier, it works like a charm for me!
Comment: Thank you! Yes, I have tried prettier before beautify, but for some reason, it doesn't work. When I click save, is not formatting properly. I have checked settings, prettier was my default formatter, yet nothing happens when I save. When I check it,  it says: "Invalid prettier configuration file detected. See log for details. ". Thank you for the file, I will keep digging on the settings for the beautify extension.


Javascript Adding a href after form is loaded

Question: I have 3 dropdowns. Only when Australia is selected from the country dropdown, I have to show a help hyperlink for the city dropdown. The user can read some guidelines when he selects Australia before he can select a city. For this I want to append the 'City' label with an a href. How can I achieve this? I tried the following but failed:
function ddCountryChange()
 {
     var ddCountry = document.getElementById("ddCountry");
     var tbCity = document.getElementById("tbCity ");
     if (ddCountry.value == "AUS"){
            tbCity.innerHTML = '
[Help] City :

<input name="ctl02$ctl00$GXDivLeft$TbCity$TbBox" type="text" maxlength="64" id="ctl02_ctl00_GXDivLeft_TbCity_TbBox" autocomplete="off">

<input type="image" name="ctl02$ctl00$GXDivLeft$TbCity$Btn" id="ctl02_ctl00_GXDivLeft_TbCity_Btn" align="ABSMIDDLE" src="/ucommand/CRM/images/icn/DropDown.gif" alt="Show List" onclick="javascript:onAutoCompleteViewList("ctl02_ctl00_AcCity");return false;" style="border-width:0px;">
';
        }
 }

While debugging through Firebug, I see that the city label is appended with a 'Help', but once the process finishes, the 'Help' disappears.
Comment: Its not clear what your specifically trying to do or what issues you are having with your attempt
Comment: Unrelated: in your `onclick` attribute, don't start it with `javascript:` - the attribute value is already javascript.
Comment: What type of element is `tbCity`? Is it a ``, ``, ``, or something else? It would really help our understanding if you simply showed the associated HTML markup.
Answer: Assuming ddCountry is the select element
 // Detect when value is changed
ddCountry.addEventListener("change", function(e){

  // Is its value now "AUS"?
  if(this.value == "AUS"){
      // Do stuff such as appending whatever label
  }else{
      // Hide stuff again?
  }

});


Angular drag and drop list nested

Question: I'm following this link
    http://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/advanced
    for build a nested drag and drop. I have parent and child items, for parent items it working fine, i have added a list in  dnd-list="ItemsParent"  and dropped items for parent are added in this list.
    I have second list for child items dnd-list="ItemsChild" when i dropped child items, items are getting added in parent list. Pleas suggest me how i can solve this issue.
Below is small part of my code:
<div `dnd-list`=`ItemsParent`>

          {{chItems.Name }}

Answer: I think, Probably you are not maintaining parent and child relationship. Your code should look like this
Below is small part of my code:

          {{chItems.Name }}

Hope this will help you out.
Comment: Thanks, But for this issue i have disabled the parent if i want to move items of child.

Angular drag and drop list nested


cytoscape doesn't display edge labels and attributes for GraphML file?

Question: I import the "tinkerpop-classic.xml", which is graphML file from the TinkerPop gremlin's sample data directory  into Cytoscape. However, it doesn't show the labels and attributes on the Edge. How can I show the full labels in both nodes and edges?
Answer: By default, Cytoscape doesn't show edge labels.  To show them, go to the Edge tab in the Style panel and create a passthrough mapping from the desired edge column to the Label.
-- scooter