text:
Q: What to do about update-initramfs errors during kernel upgrade? I just ran:
sudo apt-get update && sudo apt-get dist-upgrade

And this is the output I got from the second commands:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following NEW packages will be installed
  linux-headers-4.4.0-38 linux-headers-4.4.0-38-generic
  linux-image-4.4.0-38-generic linux-image-extra-4.4.0-38-generic
  linux-signed-image-4.4.0-38-generic
The following packages will be upgraded:
  linux-generic linux-headers-generic linux-image-generic linux-libc-dev
  linux-signed-generic linux-signed-image-generic
6 to upgrade, 5 to newly install, 0 to remove and 0 not to upgrade.
Need to get 69.3 MB of archives.
After this operation, 296 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-image-4.4.0-38-generic amd64 4.4.0-38.57 [18.7 MB]
Get:2 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-image-extra-4.4.0-38-generic amd64 4.4.0-38.57 [39.0 MB]
Get:3 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-generic amd64 4.4.0.38.40 [1,790 B]
Get:4 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-image-generic amd64 4.4.0.38.40 [2,300 B]
Get:5 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-signed-image-4.4.0-38-generic amd64 4.4.0-38.57 [3,990 B]
Get:6 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-signed-generic amd64 4.4.0.38.40 [1,820 B]
Get:7 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-signed-image-generic amd64 4.4.0.38.40 [2,332 B]
Get:8 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-headers-4.4.0-38 all 4.4.0-38.57 [9,948 kB]
Get:9 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-headers-4.4.0-38-generic amd64 4.4.0-38.57 [785 kB]
Get:10 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-headers-generic amd64 4.4.0.38.40 [2,274 B]
Get:11 http://archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-libc-dev amd64 4.4.0-38.57 [838 kB]
Fetched 69.3 MB in 1min 26s (806 kB/s)
Selecting previously unselected package linux-image-4.4.0-38-generic.
(Reading database ... 248254 files and directories currently installed.)
Preparing to unpack .../linux-image-4.4.0-38-generic_4.4.0-38.57_amd64.deb ...
Done.
Unpacking linux-image-4.4.0-38-generic (4.4.0-38.57) ...
Selecting previously unselected package linux-image-extra-4.4.0-38-generic.
Preparing to unpack .../linux-image-extra-4.4.0-38-generic_4.4.0-38.57_amd64.deb ...
Unpacking linux-image-extra-4.4.0-38-generic (4.4.0-38.57) ...
Preparing to unpack .../linux-generic_4.4.0.38.40_amd64.deb ...
Unpacking linux-generic (4.4.0.38.40) over (4.4.0.36.38) ...
Preparing to unpack .../linux-image-generic_4.4.0.38.40_amd64.deb ...
Unpacking linux-image-generic (4.4.0.38.40) over (4.4.0.36.38) ...
Selecting previously unselected package linux-signed-image-4.4.0-38-generic.
Preparing to unpack .../linux-signed-image-4.4.0-38-generic_4.4.0-38.57_amd64.deb ...
Unpacking linux-signed-image-4.4.0-38-generic (4.4.0-38.57) ...
Preparing to unpack .../linux-signed-generic_4.4.0.38.40_amd64.deb ...
Unpacking linux-signed-generic (4.4.0.38.40) over (4.4.0.36.38) ...
Preparing to unpack .../linux-signed-image-generic_4.4.0.38.40_amd64.deb ...
Unpacking linux-signed-image-generic (4.4.0.38.40) over (4.4.0.36.38) ...
Selecting previously unselected package linux-headers-4.4.0-38.
Preparing to unpack .../linux-headers-4.4.0-38_4.4.0-38.57_all.deb ...
Unpacking linux-headers-4.4.0-38 (4.4.0-38.57) ...
Selecting previously unselected package linux-headers-4.4.0-38-generic.
Preparing to unpack .../linux-headers-4.4.0-38-generic_4.4.0-38.57_amd64.deb ...
Unpacking linux-headers-4.4.0-38-generic (4.4.0-38.57) ...
Preparing to unpack .../linux-headers-generic_4.4.0.38.40_amd64.deb ...
Unpacking linux-headers-generic (4.4.0.38.40) over (4.4.0.36.38) ...
Preparing to unpack .../linux-libc-dev_4.4.0-38.57_amd64.deb ...
Unpacking linux-libc-dev:amd64 (4.4.0-38.57) over (4.4.0-36.55) ...
Setting up linux-image-4.4.0-38-generic (4.4.0-38.57) ...
Running depmod.
update-initramfs: deferring update (hook will be called later)
Examining /etc/kernel/postinst.d.
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-38-generic /boot/vmlinuz-4.4.0-38-generic
run-parts: executing /etc/kernel/postinst.d/dkms 4.4.0-38-generic /boot/vmlinuz-4.4.0-38-generic
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-38-generic /boot/vmlinuz-4.4.0-38-generic
update-initramfs: Generating /boot/initrd.img-4.4.0-38-generic

gzip: stdout: No space left on device
E: mkinitramfs failure cpio 141 gzip 1
update-initramfs: failed for /boot/initrd.img-4.4.0-38-generic with 1.
run-parts: /etc/kernel/postinst.d/initramfs-tools exited with return code 1
Failed to process /etc/kernel/postinst.d at /var/lib/dpkg/info/linux-image-4.4.0-38-generic.postinst line 1052.
dpkg: error processing package linux-image-4.4.0-38-generic (--configure):
 subprocess installed post-installation script returned error exit status 2
dpkg: dependency problems prevent configuration of linux-image-extra-4.4.0-38-generic:
 linux-image-extra-4.4.0-38-generic depends on linux-image-4.4.0-38-generic; however:
  Package linux-image-4.4.0-38-generic is not configured yet.

dpkg: error processing package linux-image-extra-4.4.0-38-generic (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of linux-image-generic:
 linux-image-generic depends on linux-image-4.4.0-38-generic; however:
  Package linux-image-4.4.0-38-generic is not configured yet.
 linux-image-generic depends on linux-image-extra-4.4.0-38-generic; however:
  Package linux-image-extra-4.4.0-38-generic is not configured yet.

dpkg: error processing package linux-image-generic (--configure):
 dependency problems - leaving unconfigured
Setting up linux-headers-4.4.0-38 (No apport report written because the error message indicates it's a follow-up error from a previous failure.
                                                               No apport report written because the error message indicates it's a follow-up error from a previous failure.
           4.4.0-38.57) ...
Setting up linux-headers-4.4.0-38-generic (4.4.0-38.57) ...
Examining /etc/kernel/header_postinst.d.
run-parts: executing /etc/kernel/header_postinst.d/dkms 4.4.0-38-generic /boot/vmlinuz-4.4.0-38-generic
Setting up linux-headers-generic (4.4.0.38.40) ...
dpkg: dependency problems prevent configuration of linux-generic:
 linux-generic depends on linux-image-generic (= 4.4.0.38.40); however:
  Package linux-image-generic is not configured yet.

dpkg: error processing package linux-generic (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of linux-signed-image-4.4.0-38-generic:
 linux-signed-image-4.4.0-38-generic depends on linux-image-4.4.0-38-generic (= 4.4.0-38.57); however:
  Package linux-image-4.4.0-38-generic is not configured yet.

No apport report written because MaxReports has already been reached
                                                                    No apport report written because MaxReports has already been reached
                                                        dpkg: error processing package linux-signed-image-4.4.0-38-generic (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of linux-signed-image-generic:
 linux-signed-image-generic depends on linux-signed-image-4.4.0-38-generic; however:
  Package linux-signed-image-4.4.0-38-generic is not configured yet.
 linux-signed-image-generic depends on linux-image-extra-4.4.0-38-generic; however:
  Package linux-image-extra-4.4.0-38-generic is not configured yet.

dpkg: error processing package linux-signed-image-generic (--configure):
 dependency problems - leaving unconfigured
No apport report written because MaxReports has already been reached
                                                                    dpkg: dependency problems prevent configuration of linux-signed-generic:
 linux-signed-generic depends on linux-signed-image-generic (= 4.4.0.38.40); however:
  Package linux-signed-image-generic is not configured yet.

dpkg: error processing package linux-signed-generic (--configure):
 dependency problems - leaving unconfigured
Setting up linux-libc-dev:amd64 (4.4.0-38.57) ...
No apport report written because MaxReports has already been reached
                                                                    Errors were encountered while processing:
 linux-image-4.4.0-38-generic
 linux-image-extra-4.4.0-38-generic
 linux-image-generic
 linux-generic
 linux-signed-image-4.4.0-38-generic
 linux-signed-image-generic
 linux-signed-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

As you can see, I had lots of errors with update-initramfs. I am scared to restart now as the installation went so badly.
The issue led me to this bug report, but I'm still not exactly too sure what to do as this has never happened before. Why is this happening now and how exactly do I fix it? It talks about there not being enough space somewhere, why is this?
I am running Ubuntu GNOME 16.04.1 with GNOME 3.20.

A: Your computer is out of disk space.
Free up some in /boot.
Then rerun the command.
Update: In chat we found that the /boot partition was full. This is where disk space should be freed.
Update 2: Doing ls /boot should show some vmlinuz-X.XX.XX files. Do apt-get purge linux-image-X.XX.XX-generic for each one. Just keep the latest one in case the one you install doesn't work. (Thanks to edwinksl for requesting information on how to do this).

A: Hopefully this well help someone else.
I was trying to manually install a newer kernel version some months ago, with similar results to OP.
Even though /boot is only 30% full I was getting the same out of disk space error when running apt-get autoremove, it would try to build the initramfs for the new kernel every time and fail.
Based on this AskUbuntu question  I moved the offending Kernel file from /var/lib/initramfs-tools and was able to get apt-get running again without errors.

A: The reason might be that you are running out of free disk space (maybe because you created a too small /boot partition on your hard disk) and you are having too many old kernels installed.
The most proper way to clean up old kernels completely, is to remove them with this command :
sudo apt purge linux-headers-* linux-headers-*-generic linux-image-*-generic linux-image-extra-*-generic linux-signed-image-*-generic

To check which kernel versions currently are installed on the system ... execute this command :
sudo dpkg --get-selections | grep linux

Replace * with the kernel versions (for instance : 4.4.0-36) from the output of the command.
Example - this is the command to completely remove all traces from kernel version 4.4.0-36 :
sudo apt purge linux-headers-4.4.0-36 linux-headers-4.4.0-36-generic linux-image-4.4.0-36-generic linux-image-extra-4.4.0-36-generic linux-signed-image-4.4.0-36-generic

Alternatively you can use byobu from Dustin Kirkland (Canonical) to get rid of the older kernels :
sudo apt install byobu
sudo purge-old-kernels

This will remove all older kernels, but leaves the current (of course) and the one before installed.

A: As for why it was happening in Ubuntu 16.04, I have a theory:
In 16.04 unneeded kernels are supposed to be removed automatically by unattended-upgrades ran automatically as a cron job or such by default so that /boot never gets full, but I suspect that Bug #1624644 occured. Can you confirm the bug in Launchpad?


text:
Q: I dont sucess to run access procedure in c# The code in c#:
public List<Per> RunSpForAotuComplete(string storedProcName, string text)
{
  OleDbDataReader rdr =null;

  List<Per> dictionary = new List<Per>();

  OleDbConnection connection = new OleDbConnection(ConString);

  connection.Open();

  OleDbCommand cmd = new OleDbCommand(storedProcName, connection)
  {
    CommandType = CommandType.StoredProcedure
  };

  OleDbParameter parameter = new OleDbParameter("@text", text);

  cmd.Parameters.Add(parameter);
  rdr = cmd.ExecuteReader();

  if (rdr.HasRows)
  {
    while (rdr.Read())
    {
      dictionary.Add(new Per
        {
           name = rdr["semel"].ToString(),
           value = rdr["shem"].ToString(),
        });
     }
   }
}

I do not understand why if(rdr.HasRows)=false?
This procedure is written:
SELECT shem, semel
FROM TYISHUV
WHERE shem like @text +'*';

I also tried to do:

OleDbParameter parameter = new OleDbParameter("text", text);

Instead of:

OleDbParameter parameter = new OleDbParameter("@text", text);

A: update your procedure as
SELECT shem, semel
FROM TYISHUV
WHERE shem like ?;

when you add parameter,
  text = text+'*';
  cmd.Parameters.AddWithValue("@text", text);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to increase the evaluation speed of this somewhat complicated table / matrix operation? I'd like to calculate the following one-dimensional array:
OneDimArray = Table[(Norm[Sum[ MatrixA[[i,j]]VectorB[[j]],{j,N}]])^2,{i,N}]

However this takes a very long time when N goes up; for N = 1500 it already takes ~40 minutes (on my MacBook Pro).
I've heard there are certain functions in Mathematica that are optimized for speed; could I employ those (and if so: which ones?) to speed up this calculation?
Thanks a lot in advance for any help!
Steven

A: You have plenty of redundant operations here:
The equivalent code is (where a is a matrix and b is a list of 3-vectors):
Map[Norm[#]^2 &, a . b];

I have:
n = 500;
a = RandomReal[1, {n, n}];
b = RandomReal[1, {n, 3}];

oneDimArray =
   Table[(Norm[Sum[a[[i, j]] b[[j]], {j, n}]])^2, {i,
     n}]; // AbsoluteTiming
(* {46.5618, Null} *)

oneDimArrayMap = Map[Norm[#]^2 &, a.b]; // AbsoluteTiming
(* {0.000621823, Null} *)

oneDimArray == oneDimArrayMap
(* True *)

Thus, using Dot almost 70000 times faster than manual loops.


text:
Q: XAML Context Menu not closing I've got a "popup" context menu on a list box, and there are two behaviors that would seem "out-of-the-box" but I am having a tough time getting the XAML ContextMenu to behave the way I would expect...
One is that, when I pick a sub-menu (e.g. "One" or "Two"), the initial menu continues to stay open (e.g. "Menu" does not go away once I've made a selection).
Second is that the menu margins seem odd.  Left justifying Horizontally does not seem to make the main menu (e.g. "Menu") left justify...  I can work around this by tweaking the margin - but thats painful for dynamic text..
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <StackPanel>
    <ListView>
      <ListView.ContextMenu>
        <!-- StaysOpen="False" -->
        <ContextMenu>
          <!--  Background="Transparent" Margin="-8,0,-8,0" -->
          <Menu>
            <!-- StaysOpenOnClick="False" -->
            <MenuItem Header="Menu">
              <MenuItem Header="One" />
              <MenuItem Header="Two" />
            </MenuItem>
          </Menu>
        </ContextMenu>
      </ListView.ContextMenu>
      <ListViewItem Content="Red" />
      <ListViewItem Content="Orange" />
      <ListViewItem Content="Black" />
      <ListViewItem Content="Blue" />
      <ListViewItem Content="Green" />
    </ListView>
  </StackPanel>
</Page>

Any thoughts on how to make the Main menu of this popup behave?
Thanks in advance,
T

A: Try this:
    <ContextMenu>
      <MenuItem Header="Menu">
        <MenuItem Header="One" />
        <MenuItem Header="Two" />
      </MenuItem>
    </ContextMenu>

you are not supposed to have a menu inside a context menu.
you should put menuitem directly.


text:
Q: not getting expected result - array loop ok, so this is in ActionScript 3, my problem is here:
var numCols:uint = 7;
numRows:uint = 7;

row = 1;
column = 3;

total = row+column-1
for(i = 0; i < numRows; i++){
    for(j = 0; j < numCols; j++){
        if(j < column){
            array[i][j]=total--
        }else{
            array[i][j]=total++
        }
    }
}

I am expecting this result in array:
3,2,1,2,3,4....

However I get this:
3,2,1,0,1,2,3,4...

A: Problem
Your condition
if (j < column)

evaluates to true three times.

1. column = 3, j = 0, total = 3, total becomes 2
2. column = 3, j = 1, total = 2, total becomes 1
3. column = 3, j = 2, total = 1, total becomes 0

the fourth time, the else clause gets executed but by this time, your total has dropped to 0.

4. column = 3, j = 3, total = 0, total becomes 1.

Possible solution
I don't know your use case but changing
array[i][j]=total++

to
array[i][j]=++total

could be all it takes.


text:
Q: What are the other 4 Chapters of Ogre Battle? I have the Ogre Battle: The March of the Black Queen on the Playstation and Ogre Battle 64: Person of Lordly Caliber on the N64 and I just brought Tactics Ogre: Let Us Cling Together for the PSP.
I went to google the play order and when I came to wikipedia it said The March of the Black Queen was the 5th chapter, Let Us Cling Together was the 6th chapter and Person of Lordly Caliber was the 7th. There's 2 other games but it says they are side stories and even then it fall short from the missing 4 chapters which seem to come before The March of the Black Queen (as it's listed the 5th).
So what are the other 4 Chapters of the Ogre Battle series?

A: If you click through to the Ogre Battle:  The March of the Black Queen link on Wikipedia, it says

Listed as the 5th chapter of the entire saga; twenty-five years prior to the beginning of the game, Empress Endora conquered the continent of Zetegenia. During her reign, a resistance organization called the Liberation Army forms to free the continent from her rule.

So it would seem that the first four chapters are Empress Endora conquering the continent.  They have not been released as games nor on other media.  They are glimpsed only as historical background in the games.
You might find more information on Wikia although they warn about spoilers.  The Wikia for Ogre Battle: The March of the Black Queen says

It is the first installment of an episodic series (although it is supposed to be the fifth episode, the previous episodes have not yet been produced)

Confirming that the first four chapters have not been released as games and were not written in some other media prior to the games being released.
If there are names for the first four chapters, I'm not finding them.  The story seems to be that good Queen Endora of Hyland was worried about invasion from another continent and went around trying to convince the other four countries on the continent to unite.  They decided that she was wrong and weak, so they united and invaded her.  She defeated them and became the evil Empress of the continent.  It's not clear how that divides into chapters.
Note the parallels to the Star Wars saga.  In 1993 when the first game was released, the middle three movies had been released.  They skipped the first three and started with episode four.  Similarly, Ogre Battle starts in the middle of the saga and doesn't seem to have released the first four episodes in the series.  Also, in Star Wars, Darth Vader starts as a hero and becomes a villain in those skipped episodes (now released).  Similarly, Endora starts as a hero and becomes a villain prior to the first game.  Rebel alliance, etc.
I would regard the initial chapters as something of a homage to Star Wars.  This is what it looks like if no one ever fills in those historical pieces.  Contrast with the actual Star Wars, which did.

A: Starting at Chapter 5 is definitely an homage to Star Wars by the creator Yasumi Matsuno. He loves to pay homages to other works.
The other 4 Chapters do not exist and most likely never will.
It is very unlikely that the other chapters have anything to do with Endora conquering the continent, a lot of how that happens is revealed in March of the Black Queen and most of what happens is bad with very little room to tell any kind of story where heroic deeds can be shown.
A more likely plot point for a previous chapter would be that of the Five Heroes. This took place over the course of 10 years between 70-80 years before March of the Black Queen.  This would set the stage for what Endora and Rashidi would do 50 years later.
Another chapter could be the original Ogre Battle itself where the Three Knights and the Twelve Disciples fought against the Ogres thousands of years ago.
But all of it is pure speculation unless you can get Matsuno himself to tell you on twitter.


text:
Q: How to replace the last octet of IP address in ARM template I am trying to pass a parameter with an IP address prefix (say, 10.0.0.0/24) in an ARM template to deploy a VNET
In the ARM template, I would like to replace 10.0.0.0/24 with 10.0.0.123 and assign it to a NIC which I would like to use later to create a VM.
I was hoping is there any way to achieve this using an ARM template?

A: Well, there is no pretty way of doing this, easiest one:
"var1": "[first(split(parameters('addressPrefix'), '/'))]",
"var2": "[substring(variables('var1'), 0, sub(length(variables('var1'), 1)))]"
"var3": "[concat(variables('var2'), 'ipgoeshere')]"

alternatively you can just chop out last 4 characters and concat ip address, or split and concat parts into an ip address:
"var1": "[first(split(parameters('addressPrefix'), '/'))]",
"var2": "[concat(variables('var1')[0], '.', variables('var1')[1], '.', variables('var1')[2], '.ipgoeshere')]"

A: You can use "privateIPAllocationMethod": "Static" and specify the private IP address, like this:
"ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAllocationMethod": "Static",
              "privateIPAddress": "[parameters('privateIPAddress')]",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses',parameters('publicIPAddressName'))]"
              },
              "subnet": {
                "id": "[parameters('subnetRef')]"
              }
            }
          }
        ]

Here an example template about static private IP address, please refer to it.

A: I'm doing like that
"variables" : {
    "subnetAddress" : "[first(split(parameters('subnetAddressWithMask'), '/'))]",
    "subnetOctets3" : "[take(split(variables('subnetAddress'), '.'), 3)]",
    "subnetNetwork" : "[concat(variables('subnetOctets3')[0], '.', variables('subnetOctets3')[1], '.', variables('subnetOctets3')[2])]"
  },
  "outputs": {
    "subnetAddress" : {
    "type": "string",
    "value" : "[variables('subnetAddress')]"
    },
    "subnetOctets3" :
    {

    "type": "array",
    "value" :  "[variables('subnetOctets3')]"
    }
   ,
    "subnetNetwork" : {
"type" : "string",
"value" :     "[variables('subnetNetwork')]"

    }

with output
  "Outputs": {
    "deploymentAppGw": {
      "Type": "Object",
      "Value": {
        "subnetAddress": {
          "type": "String",
          "value": "10.0.0.0"
        },
        "subnetOctets3": {
          "type": "Array",
          "value": [
            "10",
            "0",
            "0"
          ]
        },
        "subnetNetwork": {
          "type": "String",
          "value": "10.0.0"
        }
      }
    }
  },

Later I'm using it in this way: "[concat(variables('subnetNetwork'), '.', copyIndex(10))]" or in similar way.


text:
Q: If $(x_1,x_2,x_3)\times (1,3,1)=(2,1,6)$ then find $ (x_1,x_2,x_3).$ If $(x_1,x_2,x_3)\times (1,3,1)=(2,1,6)$ then find $ (x_1,x_2,x_3).$ Here $\times$  denotes the vector product.
The choices of answer are:
$A)(0,0,1)$
$B)(-1,2,7)$
$C)(-m,0,1-m)$ for all real $m$
$D)$There does not exist any expression $(x_1,x_2,x_4)$ in $\mathbb R^3.$

A: Hint: Given two vectors $v$ and $w$, then $v\times w$ is orthogonal to both $v$ and $w$.

A: Note that by definition of cross product if
$$\vec w = \vec v \times \vec u \implies \vec w \perp \vec v,\vec u \iff \vec w\cdot\vec v=0,\quad\vec w\cdot\vec u=0$$
but in this case the dot product
$$(1,3,1)\cdot(2,1,6)=2+3+6=11\neq0$$
thus there does not exist any expression $(x_1,x_2,x_4)$ in $\mathbb{R^3}$ such that
$$(x_1,x_2,x_3)\times (1,3,1)=(2,1,6)$$


text:
Q: Large Number of ACPI Interrupts I'm wondering if anyone has seen this before, and could perhaps shed some light on a solution.
I'm running Red Hat Enterprise Linux 6.1, fully updated in a text-only server configuration, and the kacpid and kacpi_notify processes have started to take up ~70% and ~15% of CPU time, respectively. I've traced the problem to what looks like an insane amount of ACPI interrupts:
[root@centauri ~]# cat /proc/interrupts | grep acpi; sleep 5; cat /proc/interrupts | grep acpi
  9:     447753          0   32693472          0   IO-APIC-fasteoi   acpi
  9:     447753          0   32850749          0   IO-APIC-fasteoi   acpi

At over 30k interrupts a second, something is clearly wrong. Additionally, if I check another server with a very similar hardware configuration, the interrupt counts for this particular interrupt is always zero.  Both systems are running Core i7 2600K processors with hyper-threading disabled. I've tried resetting all defaults in the BIOS, with no luck.
Any ideas what could cause such a high number of interrupts?
If I boot with acpi=off, this problem goes away.  Besides power control, are there any drawbacks to running the system with ACPI disabled?


text:
Q: Character buffer being overrun while reading file I'm trying to read data from a file but I'm getting a STATUS_STACK_BUFFER_OVERRUN error and the app crashes.
I have a struct:
struct BSPEntities
{
    char* ents;
};

And I'm reading the file:
BSPEntities entities
ifstream mapfile;
int size = 54506;
int offset = 5182600;

entities.ents = new char[size];
mapfile.seekg(offset, ios::beg);
mapfile.read((char *)(&entities.ents), size);

"size" and "offset" are values loaded from the file and known to be valid. I have preprocessor directives #pragma pack(1) and #pragma push around the BSPEntities struct.
Thanks.

A: &entities.ents is a pointer to a pointer to char.  The object pointed to (a pointer to char) is probably only 4 or 8 bytes depending on the architecture you're targeting, but you're trying to write 54,506 bytes to it.  Obviously 54,506 is larger than 8, so you're writing past the end of the pointer, and the behavior is undefined.
That read should just be mapfile.read(entities.ents, size);
Also you don't need to mess around with #pragma pack here, unless there's something more complicated going on that you're not showing.

A: mapfile.read((char *)(&entities.ents), size);

Should be
mapfile.read(entities.ents, size);

Instead of passing the address of the heap memory block that ents points to, you are passing the address of ents itself. And since ents is being allocated on the stack, you are reading bytes onto the stack until it overruns.


text:
Q: Whats wrong with my SQLite query? Error:

android.database.sqlite.SQLiteException: near "-": syntax error (code 1): , while compiling: CREATE TABLE new_info(user-name TEXT,user_mob TEXT,user_email TEXT);

Code:
public String CREATE_QUERY="CREATE TABLE "+ UserContract.addnew.TABLE_NAME+"("+ UserContract.addnew.USER_NAME+" TEXT,"
            + UserContract.addnew.MOBILE+" TEXT,"+ UserContract.addnew.EMAIL+" TEXT);";

A: As you can see in the query it tries to execute: CREATE TABLE new_info(user-name TEXT,user_mob TEXT,user_email TEXT); You have - instead of _. Just replace user-name with user_name.
Check this post to understand how to be able to use hyphen in the table names.


text:
Q: convert String to date but i get today instead I want to convert a given String from JSON in format "YYYY-MM-DD HH:MM:SS" to a Date so I can convert it to a Calendar and finally get mills from that Specific date and to day.
but I just get Today instead of given date
public static String getGameRemainedTime(String date){

        Log.i("TIME", date);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date convertedDate = new Date();
        try {
            convertedDate = dateFormat.parse(date);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.i("TIME", convertedDate+"");

        Calendar game_date = Calendar.getInstance();
        game_date.setTime(convertedDate);
        Calendar today = Calendar.getInstance();

        long gamedate_stamp = game_date.getTimeInMillis();
        long today_stamp = today.getTimeInMillis();

        Log.i("TIME", today_stamp+"-"+gamedate_stamp);

        long diff = gamedate_stamp - today_stamp;

        long day = diff / (1000 * 24 * 60 * 60 );

        long hour =  (diff -(1000 * 24 * 60 * 60 )) / (1000  * 60 * 60 );

        long mins =  ((diff -(1000 * 24 * 60 * 60 )) / (1000  * 60 * 60 )) / (1000  * 60 );

        Log.i("TIME", day+"-"+hour+"-"+mins);

        return day+"-"+hour+"-"+mins;

    }

A: You need to subtract the today_date from your specified date that why you are getting wrong results.
try to change this:
 long diff = gamedate_stamp - today_stamp;

to:
 long diff = today_stamp- gamedate_stamp ;

edit:
public static String getGameRemainedTime(String date) throws java.text.ParseException{

    Log.i("TIME", date);

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Log.i("TIME", convertedDate+"");

    Calendar game_date = Calendar.getInstance();
    game_date.setTime(convertedDate);
    Calendar today = Calendar.getInstance();

    long gamedate_stamp = game_date.getTimeInMillis();
    long today_stamp = today.getTimeInMillis();

    Log.i("TIME", today_stamp+"-"+gamedate_stamp);

    long diff =  today_stamp - gamedate_stamp;

    long day = diff / (24 * 60 * 60 * 1000);

    long hour =  diff / (60 * 60 * 1000);

    long mins =  diff / (60 * 1000);;

    Log.i("DAY: ", " " + day);
    Log.i("HOUR: ", " " + hour);
    Log.i("MINUTES", " " + mins);

    return day+"-"+hour+"-"+mins;

}

try this in your oncreate();
getGameRemainedTime("2014-5-16 10:34:22");

result:
06-14 10:37:11.891: I/DAY:(1270):  29
06-14 10:37:11.891: I/HOUR:(1270):  696
06-14 10:37:11.891: I/MINUTES(1270):  41762

A: Your SimpleDateFormat has a different format from the String you're trying to parse (it's missing the space ' ' after dd. I'm guessing the dateFormat.parse() will throw an exception, so your convertedDate will keep the value assigned with new Date(), which is the date now.

A: The format in your code is different form the format you want:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");

and you want this:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


text:
Q: orientation change sound Good morning,
We have developed an android app, and I have been charged with finding out how to remove the undesired behavior of a notification sound every time that the screen orientation changes. Obviously this behavior only exists on devices running OS version 3.2.3 or later.
I have read several posts that indicate that this can be turned off by unchecking USB Debugging in the Settings --> Developer options, however this option is not checked and none of the other apps that are on any of our Android devices make this notification sound upon orientation change.
The application does require there to be a notification when a "message is received" (the app connects to a webservice and gets new messages from the service every so often). So this would rule out any solution that disabled notifications.
Thus far, I have tried several potential solutions:
1) When a message is received, instantiate a new NotificationManager, and after the notification is sounded, destroy the NotificationManager.
if(MessageReceived == true) {
    String ns = Context.NOTIFICATION_SERVICE;
    messageNotifyManager = (NotificationManager) getSystemService(ns);
}
showNotification();
messageNotifyManager = null;

2) I realize that an orientation change is essentially the view being destroyed and re-created. I put set a flag in the initial onCreate method and checked to see if that flag had value before recreating the Notification Manager.
public static int Flag = 0;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(Flag == 0) {
        String ns = Context.NOTIFICATION_SERVICE;
  messageNotifyManager = (NotificationManager) getSystemService(ns);
        Flag = 1;
    }
}

3) In the application's main class, I created a public OrientationEventListener property and then set its value in the onCreate method, disabling it immediately. When that didn't disable the sound I tried disabling the property in every class that referenced the application's main class.
public OrientationEventListender listener;
@Override
public void onCreate() {
    super.onCreate();
    appContext = getApplicationContext();
    GetPreferences();
    //...
    listener = new OrientationEventListener(appContext){
        public void onOrientationChanged(int Orientation){
        }
    };
    listener.disable();
}

Now, as you can probably tell, I am very new to Android development. I assume that this solution is something so simple that everyone knows, and that is why there are no answers anywhere handy on the web. But any help with this simple problem would be greatly appreciated. Thanks!

A: This issue was solved by modifying the AndroidManifest, adding the following tag to each activity: android:configChanges="orientation"


text:
Q: Android Fragments, Json Parsing, return statement in doInBackground() method I am having problem when developing a weather app using Android Studio. The doInBackGround() method requires a return statement, but it shows error when I am returning forecastJsonStr (line no.181) . It says i need to return String[] and not String value. Similar return statement is asked in line 283. It says return statement missing.
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListAdapter;
    import android.widget.ListView;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    //import java.sql.Time;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import android.text.format.Time;
    import static com.github.afrin14.sunshine.R.id.container;

    public class ForecastFragment extends Fragment {

        public ForecastFragment() {
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.forecastfragment, menu);
         }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == R.id.action_refresh) {
                FetchWeatherTask weatherTask = new FetchWeatherTask();
                weatherTask.execute("94043");
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup
     container, Bundle savedInstanceState) {
           String[] forecastArray = {
                    "Today - Sunny - 88/63",
                    "Tomorrow - Foggy - 70/40",
                    "Wed - Cloudy - 72/63",
                    "Thurs - Asteroids - 75/65",
                    "Fri - Heavy Rain - 65/56",
                    "Sat - HELP TRAPPED IN WEATHERSTATION 60/51",
                    "Sun - Sunny - 80/68",
            };
            List<String> weekForecast = new ArrayList<String>
    (Arrays.asList(forecastArray));

            ListAdapter mForecastAdapter = new ArrayAdapter<String>(
                    getActivity(),
                    R.layout.list_item_forecast,
                    R.id.list_item_forecast_textview,
                    weekForecast);
            View rootView = inflater.inflate(R.layout.fragment_main,
    container, false);

            ListView listView = (ListView)
    rootView.findViewById(R.id.listview_forecast);
            listView.setAdapter(mForecastAdapter);

            return rootView;
        }

        public class FetchWeatherTask extends AsyncTask<String, Void,
    String[]> {

            private final String LOG_TAG =
                FetchWeatherTask.class.getSimpleName();

            @Override
            protected String[] doInBackground(String... params) {

                if (params.length == 0) {
                    return null;
                }

                // These two need to be declared outside the try/catch
                // so that they can be closed in the finally block.
                HttpURLConnection urlConnection = null;
                BufferedReader reader = null;
               // Will contain the raw JSON response as a string.
               String forecastJsonStr = null;

                String forecastsonStr = null;

                String format = "json";
                String units = "metric";
                int numDays = 7;

                try {
                    // Construct the URL for the OpenWeatherMap query
                    // Possible parameters are avaiable at OWM's forecast
                    //  API page, at
                    // http://openweathermap.org/API#forecast
                    final String FORECAST_BASE_URL =
          "http://api.openweathermap.org/data/2.5/forecast/daily?";
                    final String QUERY_PARAM = "q";
                    final String FORMAT_PARAM = "mode";
                    final String UNITS_PARAM = "units";
                    final String DAYS_PARAM = "cnt";

                    Uri builtUri =
  Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]).appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units).appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();

            URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");

            Log.v(LOG_TAG, "Buit URI " + builtUri.toString());
            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();
            Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
        }
        catch (IOException e) {
            Log.e(LOG_TAG, "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }

        try{
            return getWeatherDataFromJson(forecastJsonStr, numDays);
        }catch(JSONException e){
            Log.e(LOG_TAG, e.getMessage(), e);
            e.printStackTrace();
          }
                return forecastJsonStr;
     }

    /* The date/time conversion code is going to be moved outside the
     *asynctask later,
     * so for convenience we're breaking it out into its own method now.
     */
    private String getReadableDateString(long time){
        // Because the API returns a unix timestamp (measured in seconds),
        // it must be converted to milliseconds in order to be converted to
       //valid date.
        SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM
         dd");
        return shortenedDateFormat.format(time);
    }

    /**
     * Prepare the weather high/lows for presentation.
     */
    private String formatHighLows(double high, double low) {
        // For presentation, assume the user doesn't care about tenths of a
        //degree.
        long roundedHigh = Math.round(high);
        long roundedLow = Math.round(low);

        String highLowStr = roundedHigh + "/" + roundedLow;
        return highLowStr;
    }

    /**
     * Take the String representing the complete forecast in JSON Format and
     * pull out the data we need to construct the Strings needed for the
     *wireframes.
     *
     * Fortunately parsing is easy:  constructor takes the JSON string and
     *converts it
     * into an Object hierarchy for us.
     */
    private String[] getWeatherDataFromJson(String forecastJsonStr, int
     numDays)
            throws JSONException {

        // These are the names of the JSON objects that need to be
        //extracted.
        final String OWM_LIST = "list";
        final String OWM_WEATHER = "weather";
        final String OWM_TEMPERATURE = "temp";
        final String OWM_MAX = "max";
        final String OWM_MIN = "min";
        final String OWM_DESCRIPTION = "main";

        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        // OWM returns daily forecasts based upon the local time of the city
        //that is being
        // asked for, which means that we need to know the GMT offset to
        //translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always
        //the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a
        //mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(),
        dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        String[] resultStrs = new String[numDays];
        for(int i = 0; i < weatherArray.length(); i++) {
            // For now, using the format "Day, description, hi/low"
            String day;
            String description;
            String highAndLow;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // The date/time is returned as a long.  We need to convert that
            // into something human-readable, since most people won't read
            //"1400356800" as
            // "this saturday".
            long dateTime;
            // Cheating to convert this to UTC time, which is what we want
           //anyhow
            dateTime = dayTime.setJulianDay(julianStartDay+i);
            day = getReadableDateString(dateTime);

            // description is in a child array called "weather", which is 1
            //element long.
            JSONObject weatherObject =
            dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);

            // Temperatures are in a child object called "temp".  Try not to
             //name variables
            // "temp" when working with temperature.  It confuses everybody.
                    JSONObject temperatureObject =
                   dayForecast.getJSONObject(OWM_TEMPERATURE);
                    double high = temperatureObject.getDouble(OWM_MAX);
                   double low = temperatureObject.getDouble(OWM_MIN);

            highAndLow = formatHighLows(high, low);
                    resultStrs[i] = day + " - " + description + " - " +
           highAndLow;
                }

                return resultStrs;
            }
            @Override
            protected String[] doInBackground(String... params){
                if(params.length == 0){
                    return null;
                }
            }

        }
    }

A: The first generic of your AsyncTask is defining what is returned in the doInBackground method. If you want to return a String instead of a String array (String[]) than change the async task to extend:
AsyncTask<String, Void, String>

and change the doInBackground Method to return String. If you don´t want it to return anything change it to "Void".
In your second AsyncTask doInBackground method (Why do you even have two of them?) the problem is that the method only returns something (null) when your if clause is true, otherwise nothing is returned. You should also return something in the else case.
To fully understand what the generics and return types are for I recommend you to read the AsyncTask docummentation

A: You have initialized Async task with return type String array.
 public class FetchWeatherTask extends AsyncTask<String, Void, String[]>

Change the initialization as below to String to make it work.
public class FetchWeatherTask extends AsyncTask<String, Void, String>

change the method like below
@Override
protected String doInBackground(String... params)

Now you won't get this error. Hope it helps :)

A: You have to call postExecute method to get result from your http call. I have edited your code completely. This will work as you expected.
Your code should be like this.
public class ForecastFragment extends Fragment {

    public ForecastFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.forecastfragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            FetchWeatherTask weatherTask = new FetchWeatherTask();
            weatherTask.execute("94043");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup
            container, Bundle savedInstanceState) {
        String[] forecastArray = {
                "Today - Sunny - 88/63",
                "Tomorrow - Foggy - 70/40",
                "Wed - Cloudy - 72/63",
                "Thurs - Asteroids - 75/65",
                "Fri - Heavy Rain - 65/56",
                "Sat - HELP TRAPPED IN WEATHERSTATION 60/51",
                "Sun - Sunny - 80/68",
        };
        List<String> weekForecast = new ArrayList<String>
                (Arrays.asList(forecastArray));

        ListAdapter mForecastAdapter = new ArrayAdapter<String>(
                getActivity(),
                R.layout.list_item_forecast,
                R.id.list_item_forecast_textview,
                weekForecast);
        View rootView = inflater.inflate(R.layout.fragment_main,
                container, false);

        ListView listView = (ListView)
                rootView.findViewById(R.id.listview_forecast);
        listView.setAdapter(mForecastAdapter);

        return rootView;
    }

    public class FetchWeatherTask extends AsyncTask<String, Void, String> {

        private final String LOG_TAG =
                FetchWeatherTask.class.getSimpleName();
        private int numDays = 7;

        @Override
        protected String doInBackground(String... params) {

            if (params.length == 0) {
                return null;
            }

            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String forecastJsonStr = null;
            String format = "json";
            String units = "metric";

            try {
                final String FORECAST_BASE_URL =
                        "http://api.openweathermap.org/data/2.5/forecast/daily?";
                final String QUERY_PARAM = "q";
                final String FORMAT_PARAM = "mode";
                final String UNITS_PARAM = "units";
                final String DAYS_PARAM = "cnt";

                Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]).appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units).appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();
                URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");

                Log.v(LOG_TAG, "Buit URI " + builtUri.toString());
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuilder builder = new StringBuilder();
                if (inputStream == null)
                    return null;
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line).append("\n");
                }

                if (builder.length() == 0)
                    return null;

                forecastJsonStr = builder.toString();
                Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                return null;
            } finally {
                if (urlConnection != null)
                    urlConnection.disconnect();

                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }
            return forecastJsonStr;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try{
                String[] weatherDataFromJson = getWeatherDataFromJson(s);
                // do whatever you want with the output.
            }catch(JSONException e){
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }

        }

        private String getReadableDateString(long time) {

            SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
            return shortenedDateFormat.format(time);
        }

        private String formatHighLows(double high, double low) {
            // For presentation, assume the user doesn't care about tenths of a
            //degree.
            long roundedHigh = Math.round(high);
            long roundedLow = Math.round(low);

            String highLowStr = roundedHigh + "/" + roundedLow;
            return highLowStr;
        }

        private String[] getWeatherDataFromJson(String forecastJsonStr) throws JSONException {

            // These are the names of the JSON objects that need to be
            //extracted.
            final String OWM_LIST = "list";
            final String OWM_WEATHER = "weather";
            final String OWM_TEMPERATURE = "temp";
            final String OWM_MAX = "max";
            final String OWM_MIN = "min";
            final String OWM_DESCRIPTION = "main";

            JSONObject forecastJson = new JSONObject(forecastJsonStr);
            JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

            Time dayTime = new Time();
            dayTime.setToNow();

            int julianStartDay = Time.getJulianDay(System.currentTimeMillis(),
                    dayTime.gmtoff);

            dayTime = new Time();

            String[] resultStrs = new String[numDays];
            for (int i = 0; i < weatherArray.length(); i++) {
                String day;
                String description;
                String highAndLow;
                JSONObject dayForecast = weatherArray.getJSONObject(i);
                long dateTime;
                dateTime = dayTime.setJulianDay(julianStartDay + i);
                day = getReadableDateString(dateTime);
                JSONObject weatherObject =
                        dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                description = weatherObject.getString(OWM_DESCRIPTION);
                JSONObject temperatureObject =
                        dayForecast.getJSONObject(OWM_TEMPERATURE);
                double high = temperatureObject.getDouble(OWM_MAX);
                double low = temperatureObject.getDouble(OWM_MIN);

                highAndLow = formatHighLows(high, low);
                resultStrs[i] = day + " - " + description + " - " +
                        highAndLow;
            }

            return resultStrs;
        }
    }
}

Hope this help:)


text:
Q: What are the best practices regarding cryptography when different platforms are in concern? The question is, what could be the most preferable approach one can follow while working with encryption and decryption when dealing with different platforms.
As per my knowledge , whenever one wants to work with such scenarios , he/she has to take certain things into account. Like say,

*

*Encryption/decryption Algorithm

*Padding pattern

*Character Encoding at both sides

*Cipher key and block sizes

Certainly ,the Encryption/Decryption algorithm one wants to use must be same at both the sides and i guess i can say the same thing about remaining three things.
Please suggest me the steps to follow while i work with following or similar scenarios.

*

*Encrypting in c & decrypting in java

*Encrypting in php & decrypting in java

A: Try and use container formats, such as CMS if you are really interested in interoperability. It deploys BER/DER encoded ASN.1, which is a binary encoding of a message structure (similar to XML which is a textual encoding of a message). Unfortunately not all platforms contain such message formats, but if they are supported you can be reasonably sure that they can encode / decode messages.
PHP is tricky, it either relies on openssl wrappers or the horrible mcrypt libraries.

A: I would add byte ordering (little endian versus big endian for numbers) but, as long as you pick the same algorithm (and parameters) and data formats, what is encrypted on one platform should be decryptable on the other and vice versa. This is how SSL works today, for example.

A: One very important aspect for good interoperability is standard compliance.
Good cryptographic standards come with test vectors. If the two ends implement the same specification and the relevant test cases have been verified, there are much higher chances they will successfully talk to each other.
For instance, let's say you need to derive an AES key from a password. If you use openssl, you may be tempted to use the common EVP_BytesToKey function. Unfortunately, that is not a standard derivation algorithm and you will find yourself in troubles if at the other end you don't have openssl too. Using a standard like PBKDF2 is better, because you have a clear, well-known, and widespread specification for it (RFC2898) that most libraries implement.
Unfortunately, cryptographic standards tend to focus on the primitives only and it is often necessary to graft together several ones. The "grafting" may prove to be the area where interoperability falls apart. For that reason, I suggest to use the widest possible standardized algorithm, even at the cost of some extra complexity.
For instance, if you want to encrypt something, it would be good to choose a standard authenticated mode like CCM (defined - amongst others - in RFC3610). In one go you obtain interoperability for:

*

*Encryption

*Authentication

*Padding

*Delivery of IV


text:
Q: Can the Hulk talk? I was under the impression that The Hulk was incapable of speech, but I just saw The Avengers/Avengers Assemble again, and in the scene where Loki tells The Hulk to worship him as a God, The Hulk beats Loki mercilously before saying "Puny god!"
Are there other examples of The Hulk talking?

A: There are a number of universes in which Hulk can talk normally, but just considering Earth-616, we have a few.
Joe Fixit

Gray Hulk/Joe Fixit – The Gray Hulk (though not the original) worked for a time as a Las Vegas enforcer called "Joe Fixit". The Gray Hulk has poor intelligence, although he occasionally displays knowledge and intellectual ability normally associated with Banner.

Professor Hulk

Merged/Professor Hulk – The Merged Hulk is the merger of Banner and the Savage and Gray Hulks. The Merged Hulk was later retconned into The Professor. The Professor, rather than being a merger of the three main personalities, was interpreted as a fourth, separate personality that represented Banner's ideal self. The primary difference between the two is that the Merged Hulk demonstrated aspects of the Banner, Gray Hulk and Savage Hulk personalities (also possessing Banner's intelligence, Joe Fixit's cunning, and the Savage Hulk's size and strength), while the Professor did not.

World Breaker Hulk

World Breaker Hulk – The Hulk of World War Hulk is a cunning and more powerful version than the previous incarnations. His rage is at its most focused, due to meditation training by his ally Hiroim.

It should be noted that the other versions of the Hulk are generally described as having the intelligence and temperament of a child. He can talk, he just usually doesn't. These versions I mention (amongst others from across the multi-verse) are the ones that are as intelligent as, or more intelligent than a normal person.
In the MCU
Until recently, the Hulk has demonstrated very limited ability to speak. However, Thor Ragnarok changed this and depicts Hulk having entire conversations with Thor.

A: Disney XD currently has two cartoons on the air that depict Hulk in very different ways.
In "Avengers Assemble", he is a member of the Avengers, and talks once in awhile with typical dumbed-down speech patterns.
In "Hulk and the Agents of S.M.A.S.H.", he leads his own team of hulks, and talks frequently with normal speech patterns and intelligence.

A: The latest Hulk incarnation, Doc Green, is 'the smartest there is' more intelligent than Banner, due to using the extremis virus to heal brain damage. However Doc Green has speculated that the effects of the extremis virus are temporary and he will return to a normal dumb Hulk state (Hulk 16, 2015).
Maestro Hulk, a Hulk from a future timeline, is extremely intelligent but evil (Future Imperfect 1, 2015).
The movie Hulk is a, for want of a better term, is a young Hulk. The incarnations of the Hulk that have been mentioned in this thread are older Hulks. Hulk appears to mature with age.


text:
Q: how to get arabic results in location weather search form " the api support arabic lang " how to get arabic results in location weather search form " the api support arabic lang "
i have the weather results with english lang just
when i input arabic city neme i have no results
when i replace the location name in link with arabic city name directly i have all inf i need
but when i use the search form i have the results with en lang
the code below .. what can i do to get the results with ar lang !!

<meta charset="utf-8">
<main class="container text-center"

حالة الطقس

<form class="form-inline" method="post">

يرجى ادخال موقعك
<input tupe="text" class="form-control" id="location" placeholder="location" name="location" size="100%">
<button class ="btn btn-primary" type="submit">ابحث الان</button>

</form>
----
$location = htmlentities($_POST['location']);
$location = str_replace(' ', '+', $location);
$geocode_url =  'https ://geocoder.api.here.com/6.2/geocode.json?searchtext='.$location.'&app_id=XXX&app_code=XXX';
$location_data = json_decode(file_get_contents($geocode_url));

A: Apparently this was due to the fact that the dynamically inserted value was not properly URL-encoded, so the fix is to change
searchtext='.$location.'

to
searchtext='.urlencode($location).'

When you test such a URL by directly inputting it into your browser address bar, the browser usually applies missing encoding where necessary on its own - but other systems don't necessarily do that, so you need to apply it yourself.


text:
Q: AngularJS and embedded framework html I'm developing a user preferences page and I've decided to use AngularJS to control the state of the data.
What I would like to achieve is a page that shows the current user's settings and allows a user to edit them, cancel their changes, or save & submit changes if they so desire. I've binded my labels and my input controls to the model so that when a user modifies their email address, it is reflected across correctly.
I'm basing my work off this example #3 by the way: http://code.angularjs.org/1.0.0rc12/docs-1.0.0rc12/guide/forms
My question is related to the default values for the page. Since the model is defined as an object in Javascript. In the link above, default values can be set over here in $scope.master= {}; which works fine except that I'm using a framework to generate a static page and not retrieving an json object from my server. My pages are all written in embedded scala, so I access the values serverside. What is the best way to take the info retrieved serverside and turn into an object client side javascript can access?

A: You have a few choices.  The way I would do it would be to push the initial state (through a WebSocket or something) to Angular as JSON, or have Angular pull it from the server through an HTTP call.
You could also perhaps render the page with ng-init tags to set the initial state, but this way seems weird to me.
<div ng-controller="FormController" ng-init="formData = {}">
  <form>
     <input ng-model="formData.input1" ng-init="formData.input1 = 'initialValue'>
  </form>
</div>

A: I am using ASP.NET and Dapper-Dot-Net. I use the following techniques to get my data on to the page and then into Angular scope. It should be pretty transferable to your environment.

*

*Define a DataTransferObject class in the page on the server side and a public string called DtoJson to hold the serialized version of your class instance.
private class DataTransferObject{
  public User User;
  public List<Project> Projects
}

public string DtoJson;

var dto=new DataTransferObject();
var userName="however you get a username";
dto.User=User.Get(userName);  // I already have a User class
var sql="select * from projects where user_name=:UserName";
var p=new DynamicParameters();
p.Add(":UserId", dto.User.ID);
dto.Projects=Project.Query<Project>(sql, p);  // returns a list of Project

// I use json.net to convert the Dto to json and expose it as a public variable
var DtoJson=Json.Convert(dto);  // approximate syntax but you get the idea

*On the client side I put a script tag at the head of the page and inject the DtoJson into it to get it into the global scope
<script>var dto=<%=DtoJson%>;</script>

*At the bottom of my page I have a script src="pageName.js" which is my Angular controller file. Inside the controller I say
$scope.dto=dto;
console.log($scope.dto);

*Now the json that was created on the server side is in my controller's scope and I can data bind to {{dto.User.FIRST_NAME}} and {{dto.Projects[0].ID}} ng-repeat="for p in dto.Projects" etc
I hope that that makes sense.
Peter


text:
Q: 2D Eculidian matrix to 2D cartesian graph/plan Can anyone help ?
I am trying to convert a 2D matrix of distances to a 2D graph.
For instance, I would like to go from this :
|     A  B  C  D  E  F  G
|  A  -  2  2  5  1  3  5
|  B     -  2  4  4  2  1
|  C        -  1  2  4  8
|  D           -  4  5  3
|  E              -  1  2
|  F                 -  1
|  G                    -

To this (link to image) : http://i.stack.imgur.com/j8Moa.png
To show this example, I've used photoshop and GraphViz
graph G { node [shape=circle,height=.2,width=.2]; a -- b [len=2,label="2"]; a -- c [len=2,label="2"]; a -- d [len=5,label="5"]; a -- e [len=1,label="1"]; a -- f [len=3,label="3"]; a -- g [len=5,label="5"]; b -- c [len=2,label="2"]; b -- d [len=4,label="4"]; b -- e [len=4,label="4"]; b -- f [len=2,label="2"]; b -- g [len=1,label="1"]; c -- d [len=1,label="1"]; c -- e [len=2,label="2"]; c -- f [len=4,label="4"]; c -- g [len=8,label="8"]; d -- e [len=4,label="4"]; d -- f [len=5,label="5"]; d -- g [len=3,label="3"]; e -- f [len=1,label="1"]; e -- g [len=2,label="2"]; f -- g [len=1,label="1"]; }

Does anyone know know an easy way to do that ?
I would like to do it under mathlab or java.
Thanks a lot !
References :

*

*Create a graph from a set of distances

*http://albertomurta.wikispaces.com/file/view/coordinates_from_distances.pdf

*https://stackoverflow.com/questions/13513455/drawing-a-graph-or-a-network-from-a-distance-matrix

A: If you're given distances between every pair of nodes, then your problem is seriously overdetermined, and it's unlikely that there's a solution at all unless the input data have very special properties.
For the sample data you show, the distances between A, B, and G are 2, 5, and 1, which violates the triangle inequality so you've already an impossibility on your hands there.
If you have distances that you have reason to think do admit a solution, you can use a naive point-by-point algorithm:

*

*Start by placing the first two points $A$ and $B$ horizontally beside each other on the $x$ axis with the appropriate distance.

*For each new point, look at its known distances to $A$ and $B$. Use the distance formula $\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$ to get two equations for the coordinates of $P$. Square each side of each equation to get rid of the square roots, and subtract the equations from each other in order to get rid of the $x_P^2$ and $y_P^2$ terms. Noting that $y_A$ and $y_B$ are both $0$ and $x_A$ and $x_B$ are both known, this gives you a linear equation in $x_P$ that is easily solved.

*Now you can find $y_P$, up to its sign, by the Pythagorean theorem given the distance $AB$. If this is the first point with a nonzero $y$ you place, select the sign of its $y$ arbitrarily; otherwise compute the distances between the two possible positions and a point you've already placed off-axis and choose the position that fits your data best.


text:
Q: i can't read the user storage, I' am trying to list all the folders and files from user storage, I've declared the READ_EXTERNAL_STORAGE permission in android.manifest file but I don't what's wrong, I can't read the user storage
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.button);
        button.setOnClickListener(this);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                new String[] {
                    Manifest.permission.READ_EXTERNAL_STORAGE
                }, 123);
        } else {
            Log.d(TAG, "onCreate: Permission Granted");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
        @NonNull String[] permissions,
        @NonNull int[] grantResults) {
        switch (requestCode) {
            case 123:
                if (grantResults != null && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Permission Denied",
                        Toast.LENGTH_SHORT).show();
                }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                String path = "/";
                File dir = new File(path);
                if (dir.isDirectory()) {
                    Log.d(TAG, "dir: Yes, I am!");
                }
                if (dir.canRead()) {
                    Log.d(TAG, "dir: Read me!");
                } else {
                    Log.d(TAG, "dir: you can't read me!");
                }
                if (dir.canWrite()) {
                    Log.d(TAG, "dir: use me!");
                } else {
                    Log.d(TAG, "dir: You Can't write me");
                }
        }
    }
}

log cat:  D/MainActivity: onCreate: Permission Granted 2020-05-04
  07:21:09.680 27634-27634/co.ak.externalstorage D/MainActivity: dir:
  Yes, I am! 2020-05-04 07:21:09.680 27634-27634/co.ak.externalstorage
  D/MainActivity: dir: you can't read me! 2020-05-04 07:21:09.680
  27634-27634/co.ak.externalstorage D/MainActivity: dir: You Can't write
  me

A: The "/" root directory is not readable since Android 7.
Why are you calling that user storage?


text:
Q: How to programatically select ComboBox value within Cell Factory? My TableView uses a custom CellFactory to display a ComboBox in one column, allowing the user to select from available options. Those options are loaded after the TableView is populated (as they can change based on the user's selections elsewhere in the scene).
In the MCVE below, I have two columns for my Item class: Name and Color. Within the Color column, I have the ComboBox which will display the current value of the Item's itemColor property.
You will see that the ComboBox is not populated with a list of values yet and item "Three" has no value selected.
What I need is this:
When the user clicks on the "Load Available Colors" button, the list for the ComboBox is created. The user can now select any of the available colors. However, if there is not already a value for the item's color, I want the first color in the ComboBoxes to be selected automatically; so item "Three" would now show the color "Red" as being selected.

THE MCVE

Item.java:
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class Item {

    private StringProperty itemName = new SimpleStringProperty();
    private StringProperty itemColor = new SimpleStringProperty();

    public Item(String name, String color) {
        this.itemName.set(name);
        this.itemColor.set(color);
    }

    public String getItemName() {
        return itemName.get();
    }

    public void setItemName(String itemName) {
        this.itemName.set(itemName);
    }

    public StringProperty itemNameProperty() {
        return itemName;
    }

    public String getItemColor() {
        return itemColor.get();
    }

    public void setItemColor(String itemColor) {
        this.itemColor.set(itemColor);
    }

    public StringProperty itemColorProperty() {
        return itemColor;
    }
}

Main.java:
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    // List of items
    private static ObservableList<Item> listOfItems = FXCollections.observableArrayList();

    // List of available Colors. These will be selectable from the ComboBox
    private static ObservableList<String> availableColors = FXCollections.observableArrayList();

    public static void main(String[] args) {
        launch(args);
    }

    private static void buildSampleData() {

        availableColors.addAll("Red", "Blue", "Green", "Yellow", "Black");
    }

    @Override
    public void start(Stage primaryStage) {

        // Simple Interface
        VBox root = new VBox(10);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(10));

        // Build a list of sample data. This data is loaded from my data model and passed to the constructor
        // of this editor in my real application.
        listOfItems.addAll(
                new Item("One", "Black"),
                new Item("Two", "Black"),
                new Item("Three", null),
                new Item("Four", "Green"),
                new Item("Five", "Red")
        );

        // TableView to display the list of items
        TableView<Item> tableView = new TableView<>();

        // Create the TableColumn
        TableColumn<Item, String> colName = new TableColumn<>("Name");
        TableColumn<Item, String> colColor = new TableColumn<>("Color");

        // Cell Property Factories
        colName.setCellValueFactory(column -> new SimpleObjectProperty<>(column.getValue().getItemName()));
        colColor.setCellValueFactory(column -> new SimpleObjectProperty<>(column.getValue().getItemColor()));

        // Add ComboBox to the Color column, populated with the list of availableColors
        colColor.setCellFactory(tc -> {
            ComboBox<String> comboBox = new ComboBox<>(availableColors);
            comboBox.setMaxWidth(Double.MAX_VALUE);
            TableCell<Item, String> cell = new TableCell<Item, String>() {
                @Override
                protected void updateItem(String color, boolean empty) {
                    super.updateItem(color, empty);
                    if (empty) {
                        setGraphic(null);
                    } else {
                        setGraphic(comboBox);
                        comboBox.setValue(color);
                    }
                }
            };

            // Set the action of the ComboBox to set the right Value to the ValuePair
            comboBox.setOnAction(event -> {
                listOfItems.get(cell.getIndex()).setItemColor(comboBox.getValue());
            });

            return cell;
        });

        // Add the column to the TableView
        tableView.getColumns().addAll(colName, colColor);
        tableView.setItems(listOfItems);

        // Add button to load the data
        Button btnLoadData = new Button("Load Available Colors");
        btnLoadData.setOnAction(event -> {
            buildSampleData();
        });
        root.getChildren().add(btnLoadData);

        // Add the TableView to the root layout
        root.getChildren().add(tableView);

        Button btnPrintAll = new Button("Print All");
        btnPrintAll.setOnAction(event -> {
            for (Item item : listOfItems) {
                System.out.println(item.getItemName() + " : " + item.getItemColor());
            }
        });
        root.getChildren().add(btnPrintAll);

        // Show the stage
        primaryStage.setScene(new Scene(root));
        primaryStage.setTitle("Sample");
        primaryStage.show();
    }
}

Now, with a regular ComboBox, a simple call to comboBox.getSelectionModel().selectFirst() after loading the availableColors would be fine. But since this ComboBox is created within the CellFactory, I am not sure how to update it once the list of colors is populated.

Indidentally, I use this CellFactory implementation instead of a ComboBoxTableCell because I want them to be visible without having to enter edit mode on the TableView.

A: I actually took kleopatra's advice and updated my data model to include a default value instead. I agree this is cleaner and more appropriate approach.


text:
Q: How to append to a list only the first time a prime is encountered I wrote this Python code to print all the prime numbers until 1000:
primes = []

for prime in xrange(1, 1000):
    for b in xrange(2, prime):
        if (prime % b == 0):
            break
        else:
            primes.append(prime)

print primes

However, if a number is a prime, it is appended a lot of times before moving to the next number. I tried using continue instead of break but that does not work.
I also added some more code onto that (which works) to simply output the array into a text file. It is so large that I cannot even paste it into here.
How can I append each prime number to the list only once instead of many times?

A: There's a feature in Python you can use quite effectively here.  Just change your indentation like this:
primes = []

for prime in xrange(1, 1000):
    for b in xrange(2, prime):
        if (prime % b == 0):
            break
    else:
        primes.append(prime)

print primes

That is, de-indent the else clause.  This way it is not the else of the if but of the for loop.  A for loop can have an else branch which gets executed after the loop has performed all scheduled iterations.  If there is a break called, it gets not executed.
You can use that here without having to change a lot of your original code.
Of course, in your original version, each loop iteration in which a tested number did not turn out to be a non-prime, that tested number got appended (which was not what you wanted).
Also note that 1 is not a prime number (at least since Gauss in 1801, some say even since Euclid (600BC) first wrote about prime numbers, although there were heretics since into the 19th century), so your outer loop should start at 2 instead.
But note what Daniel wrote in his answer; you do not have to step through all the way to prime because after reaching the square root of prime, you can bail out.  I always compared b * b to prime, but maybe computing sqrt(prime) once even is faster.
And of course, you can be faster by ignoring all even numbers completely.  Except 2 none are prime ;-)

A: You need to only add the number if it reaches the end of the loop without it finding a divisor.
from math import sqrt

prime = True
for b in xrange(2, sqrt(prime)):
    if prime % b == 0:
        prime = False
        break
if prime:
    primes.append(prime)

Note I've added an optimization: you only need to test up the square root of a number, because anything after that can't possibly divide.


text:
Q: Does Orange API sms sends messages to Etisalat and Vodafone? I tried to send an sms to Orange phone number and it was sent successfully! but when i tried to send to Etisalat or Vodafone number there weren't sent and the bundle decreased by two.
does orange API sms sends sms messages to Etisalat and Vodafone ?
Thank you!

A: For which country are you referring to?
If it's Egypt, then you would need to send proof of company documents for whitelisting to contact.developer@orange.com to be able to send to other operators.
This is local legislation for Egypt.
Regards,
D

A: As @Dharmesh said I have been trying so hard but you should send government and registration papers to company developer mail contact.developer@orange.com so that your messages reached outside orange operator.
As they added more detail here :

To send SMS to other operators in Egypt, after the approval of your sender names follow the steps in this document


text:
Q: References for Forcing with Side Conditions I'm looking for some good references about Forcing with Side Conditions, including expository papers that explain the main ideas with some details in order to give me a fairly clear insight of those set theoretic problems that are solvable using this approach. Any other reference is also welcome.

A: *

*S. Todorcevic, Notes on Forcing Axioms, Chapter 7.

*Itay Neeman, Forcing with side conditions. Oberwolfach, 2011. http://www.math.ucla.edu/~ineeman/

*B. Velickovic, G. Venturi, Proper forcing remastered.  http://www.math.cmu.edu/~eschimme/Appalachian/Pfr.pdf


text:
Q: Laravel 5 : the move() function doesn't save the uploaded image file What I'm trying is to set an image uploader with Laravel 5.
Here is the form.
    <form action="/edit/{{$id}}" method="POST" enctype="multipart/form-data">
        {!! csrf_field() !!}
        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
        <input type="hidden" name="_method" value="PUT">
            //There are other tags (including other input) here
            <input type="file" name="pic" accept="image/*">
        <input type="submit" value="Apply Changes">
    </form>

Here is the controller function which will be run from the form above.
public function update($id)
{
    $this->model->find($id)->fill($this->request->all())->save();
    if ($this->request->hasFile('pic')) {
        $file = $this->request->file('pic');
        $name = $file->getClientOriginalName();
        $file->move('assets/serviceimages/', $name);
    }

    return redirect('/blahblah');
}

As you might have noticed, this doesn't store the uploaded file under the assets/serviceimages/ directory, which is what I've been trying.
Basically I've been following this tutorial, but apparently I'm missing something and totally clueless about what it is, even after I had a look at the API documentation.
Inside of the if statement of the controller function, it was confirmed that the $file and $name had what I expected.
Therefore, I suspect that the problem lies in the move() function.
Any small piece of advice will be appreciated, since this is my first time that I've tried to set an uploader.

A: Permissions if you are on Linux. If that doesn't work try it this way:
$image = $request->file('pic');
$destinationPathImg = '/your path/images/';

if (!$image->move($destinationPathImg, $image->getClientOriginalName())) {
    return 'Error saving the file.';
}

Also, this need to be added in ur ()
public function update(Request $request, $id)

A: I found having to use the Storage adapter to use the full file path worked for me.
$storageAdapter = Storage::disk('v1')->getDriver()->getAdapter()

$full_path_before = $storageAdapter->applyPathPrefix($oldPath);
$full_path_after = $storageAdapter->applyPathPrefix($newPath);

if (!File::exists($full_path_before)){
   throw new \Exception("Error moving folders");
}
$move_files = $full_path_after !== $full_path_before;

if ($move_files){
   File::move($full_path_before, $full_path_after);
}

A: Use This Method This Will Work 100%
if($request->hasFile('filename')){

     $file = $request->filename;

    $file_new_name =  $file->move("upload/posts/", $file->getClientOriginalName());

    $post->filename = $file_new_names;

   }

Remember filename is your < img name="filename" >


text:
Q: Keep nav items on one line on small devices Currently my nav nav-tabs are being pushed to a next line if i make my screen smaller, however i wish to keep them on one line and enable overflow-x when they pass the 768px breakpoint.
I cannot figure out how to make this work, can anyone help?
html

Identity

Attributes

Skills

Spells

Passives

Equipment

Consumables

current css
#char-nav {
    border: none;
    margin-top: 13px;
}
.nav-tabs {
    border: none;
}
.nav > li > a {
    padding: 8px 15px;
}

@media screen and (max-width: 767px) {
    #char-nav {
        display: inline-block;
        overflow-x: scroll;
        overflow-y: hidden;
        white-space: nowrap;
        max-width: 80%;
        margin-top: 0;
    }
}

A: Here is a bit of css :
.min-width{
    overflow-x:auto
}
ul.nav{
    display:inline-flex
}

And a bootply : http://www.bootply.com/BRqVaRNnZP


text:
Q: how to change the slide speed of a viewpager The default speed is too fast, and I think it would affect the user experience.
In the gallery, we can override the onfling(), what's the solution in a viewpager?

A: The speed is determined by the screen density and is a private variable. There is no way of changing it.
A solution would be to copy the source for the ViewPager and create your own class. You can then change the value to whatever you want. The variable is mBaseLineFlingVelocity and it gets set during initViewPager().


text:
Q: SharPoint People Picker Hello Is there any People Picker Service/Web Service in SharePoint 2013?  Actually i want to check some user existence in People Picker through PowerShell. I have a list of users in  csv file.

A: Please refer the following powershell to check a user exists in a group:
$w = get-spweb http://my
$gs = $w.SiteGroups
$g = $gs[12]
$user = $g.Users.GetByEmail("user@domain.com")
if($user -eq $null){write-host "User Not Found"}


text:
Q: is System.Threading.Thread.CurrentPrincipal shared between all users? I intend to use currentprincipal and I searched that the property is static , so it must be shared, Actually I need it to be different not shared. as I write some code I see the currentprincipal is different after 2 users logged in to application, is it right , can I be sure of being different of the property? Actually my users logged in to application and call my function through WCF! please ask me to clear if my explanation is not enough, thanks in asvance

A: System.Threading.Thread.CurrentPrincipal returns IPrincipal for current thread. Do your users use the same thread at one moment? I think, no.


text:
Q: Using printf awk function to output nth arguments Given the following file's content:

alias command with whitespace-separated argument list
anotheralias othercommand and its arguments

how i can to print something like:

       alias = command with whitespace-separated argument list
anotheralias = othercommand and its arguments

Currently I'am using the below command, but it's wrong.

cat aliases | awk '{printf "%20s = %s\n", $1, $0}'

A: cat aliases | awk '{$1=sprintf("%20s =",$1);print}'

A: cat aliases | awk '{ printf("%20s =", $1); $1=""; printf("%s\n", $0) }'

A: another way:
sed 's/ /=/1' yourFile|awk -F= '{printf ("%20s = %s\n",$1,$2)}'

A: Just use the shell:
while read line; do
  set -- $line
  cmd=$1
  shift
  printf "%20s = %s\n" "$cmd" "$*"
done < filename


text:
Q: How to select rows within a table that are not in other tables I am having some bother in selecting books that are neither translated books, books series' nor book sections. The structure looks like this. (sorry, stackoverflow won't let me post an image with less than 10 reputation)
It uses class inheritance design pattern with shared primary keys.
This is what I've came up with so far:
SELECT *
FROM (
        (
            (`hedwig_db`.`refs` JOIN `hedwig_db`.`books`
                        ON `refs`.`ref_id`=`books`.`ref_id`
            )
        LEFT JOIN `hedwig_db`.`authors`
                ON `refs`.`ref_id` =  `authors`.`ref_id`
        )
    LEFT JOIN `hedwig_db`.`editors`
            ON `books`.`book_id`=`editors`.`book_id`
    )
WHERE `books`.`book_id`
NOT IN (SELECT `books`.`ref_id`,
                `books`.`book_id`,
                `book_section`.`book_id`,
                `book_translated`.`book_id`,
                `book_series`.`book_id`
        FROM(
                (
                    (`hedwig_db`.`books` JOIN `hedwig_db`.`book_translated`
                        ON `books`.`book_id`=`book_translated`.`book_id`
                    )
                JOIN `hedwig_db`.`book_section`
                    ON `books`.`book_id`=`book_section`.`book_id`
                )
            JOIN `hedwig_db`.`book_series`
                ON `books`.`book_id`=`book_series`.`book_id`
            )
    )
It's the NOT IN query that is returning nothing and I can't for the life of me figure out how to get what I'm looking for! Thanks in advance :)

A: I would simplify the where clause to just use not exists:
SELECT *
FROM `hedwig_db`.`refs` r JOIN
     `hedwig_db`.`books` b
     ON r.ref_id = b.ref_id LEFT JOIN
     `hedwig_db`.`authors` a
     ON r.ref_id =  a.ref_id LEFT JOIN
     `hedwig_db`.`editors` e
     ON b.book_id = e.book_id
WHERE NOT EXISTS (select 1 from `hedwig_db`.`book_translated` bt where bt.book_id = b.book_id) and
      NOT EXISTS (select 1 from `hedwig_db`.`series` bs where bs.book_id = b.book_id) and
      NOT EXISTS (select 1 from `hedwig_db`.`book_sections` bs where bs.book_id = b.book_id);

Your not in clause is joining the tables together, so it would be finding books that are all three.  You could do a union all instead, but I would stick with three different conditions.


text:
Q: How can I learn which css files are related this property? edit:
there is below code bottom of style.css:
/*# sourceMappingURL=style.css.map */

also there is a style.css map file.I added its code:
https://www.codepile.net/pile/azGno8Qb

I dont know anything about sass.I have a html file which made sass.I want to change its styles.However when I click the element on chrome, below link seems instead of css file on developer window:
/sass/project-sass/_header.scss : HTTP status code: 404
So, which css file is refered by _header.scss?
I need to change the element.
Also I included all css files but when I include a code snippet from this html file to wordpress, necessary properties doesnt load also there is no _header.scss on chrome developer window.
How can I include the sass stuff on wordpress?

A: It's difficult to answer your question because you don't provide the architecture of your document and code. However :
_header.scss seems to refer to a "sub" style and it could be look like in the main style :
@import url("_header.scss");

But you can't put a scss file in HTML. You must compile it before and it will result a CSS file for example :
sass _header.scss header.css

and in your HTML :
<link rel="stylesheet" href="path/to/your/header.css">


text:
Q: How does sklearn's MLP predict_proba function work internally? I am trying to understand how sklearn's MLP Classifier retrieves its results for its predict_proba function.
The website simply lists:

Probability estimates

While many others, such as logistic regression, have more detailed answers:
Probability estimates.
The returned estimates for all classes are ordered by the label of classes.

For a multi_class problem, if multi_class is set to be "multinomial"
  the softmax function is used to find the predicted probability of each
  class. Else use a one-vs-rest approach, i.e calculate the probability
  of each class assuming it to be positive using the logistic function.
  and normalize these values across all the classes.

Other model types, too, have more detail. Take for example a support vector machine classifier
And there is also this very nice Stack Overflow post which explains it in depth.

Compute probabilities of possible outcomes for samples in X.
The model need to have probability information computed at training
  time: fit with attribute probability set to True.

Other Examples
Random Forest:

Predict class probabilities for X.
The predicted class probabilities of an input sample are computed as
  the mean predicted class probabilities of the trees in the forest. The
  class probability of a single tree is the fraction of samples of the
  same class in a leaf.

Gaussian Process Classifier:
I am looking to understand the same thing as the above post, but for the MLPClassifier. How does the MLPClassifier work internally?

A: Looking within the source code, i found:
def _initialize(self, y, layer_units):

    # set all attributes, allocate weights etc for first call
    # Initialize parameters
    self.n_iter_ = 0
    self.t_ = 0
    self.n_outputs_ = y.shape[1]

    # Compute the number of layers
    self.n_layers_ = len(layer_units)

    # Output for regression
    if not is_classifier(self):
        self.out_activation_ = 'identity'
    # Output for multi class
    elif self._label_binarizer.y_type_ == 'multiclass':
        self.out_activation_ = 'softmax'
    # Output for binary class and multi-label
    else:
        self.out_activation_ = 'logistic'

It seems that MLP Classifier uses a logistic function for binary classification and a softmax function for multi-label classification in order to build the output layer. This suggests that the output of the net is a probability vector, based on which the net deduces predictions.
If I look to the predict_proba method:
def predict_proba(self, X):
    """Probability estimates.
    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The input data.
    Returns
    -------
    y_prob : ndarray of shape (n_samples, n_classes)
        The predicted probability of the sample for each class in the
        model, where classes are ordered as they are in `self.classes_`.
    """
    check_is_fitted(self)
    y_pred = self._predict(X)

    if self.n_outputs_ == 1:
        y_pred = y_pred.ravel()

    if y_pred.ndim == 1:
        return np.vstack([1 - y_pred, y_pred]).T
    else:
        return y_pred

That confirms the action of a softmax or a logistic as activation function for the output layer in order to have a probability vector.
Hoping this can help you.


text:
Q: Using GL Studio video in Unity My software guys are trying to figure out if it's possible to have video being generated by GL Studio (OpenGL) to display in game on a material.
In a nutshell, we have GL Studio creating videos for display units on the fly based on inputs from the user. We are trying to get that video that is being created to show up in game. Is there a way to grab that video that was being rendered in a window before and have a material display it in game instead?

A: I havent heard of GL Studio being integrated into Unity this way.  Did you ask GL Studio support? support@disti.com
Cheers,
Jonathan


text:
Q: Toggle with ng-show not working in directive I have directive that brings up the sidebar in my application.
I tried to write some code to toggle some content inside this sidebar.
But when I trigger the toggle function nothing happens.
This is my directive:
menuItem.directive("menuItem", function() {
 return {
     restrict: "E",
     template: "

",
     transclude: true,
     scope: {
         hash: "@"
     },
     link: function($scope) {
         $scope.toggle = function(e) {
             $scope.test = !$scope.test;
             console.log($scope.test);
             $scope.$apply(); // This here brings up error $rootScope: inprog
         }
     }
 }
});

And here is my html:
 <menu visible="leftVisible" alignment="left">
                          <menu-item hash="first-page">

                                  Testing

1

2

                          </menu-item>
                </menu>

How should I resolve this problem, to make the ul toggleable?

A: The reason is that your directive and your template have different scopes. When you change test field inside toggle method, you change it in directive scope, whereas ng-show directive uses variable from controller scope. And your directive should not depend on controller's markup (and controller-specific variables, like test). You can create a variable binding in your directive so that it will be responsible for changing visibility and controller markup will be responsible for using this variable to show or hide your menu items. Here is a markup for your controller
<menu visible="leftVisible" alignment="left">
    <menu-item hash="first-page" show="someVar">

            Testing

1

2

    </menu-item>
</menu>

And here is a code for your directive
menuItem.directive("menuItem", function () {
    return {
        restrict: "E",
        template: "

",
        transclude: true,
        scope: {
            hash: "@",
            show: '='
        },
        link: function ($scope) {
            $scope.toggle = function (e) {
                $scope.show = !$scope.show;
            }
        }
    }
});

In this case your directive doesn't depend on myVar variable. It controls visibility using show attribute. I've also removed $apply call since your handler called using ng-click directive which means that angular is aware of possible changes and you don't have to explicitly start digest cycle.


text:
Q: Log ping and date isn't working :START
echo %date% %time% && ping -n 1 192.168.1.1 >> pingReport.txt 2>&1
echo %date% %time% && ping -n 1 192.168.1.2 >> pingReport.txt 2>&1
echo %date% %time% && ping -n 1 192.168.1.3 >> pingReport.txt 2>&1
echo %date% %time% && ping -n 1 192.168.1.4 >> pingReport.txt 2>&1
goto START

This echos Date and time on my screen only, but not into the file.
How can I get date and time in the txt file too?

A: echo and ping are two commands separated by "&&".
The way you wrote it, the second command (after "&&") is sent to the text file.
If you want both commands output to be sent to the text file, you can put them inside parentheses:
:START
(echo %date% %time% && ping -n 1 192.168.1.1) >> pingReport.txt 2>&1
(echo %date% %time% && ping -n 1 192.168.1.2) >> pingReport.txt 2>&1
(echo %date% %time% && ping -n 1 192.168.1.3) >> pingReport.txt 2>&1
(echo %date% %time% && ping -n 1 192.168.1.4) >> pingReport.txt 2>&1
goto START


text:
Q: Scroll is Not Working Inside SetTimeout() with Delay I have an scroll to element snippet as:
$('html,body').animate({
     scrollTop: $(window.location.hash).offset().top
},1000);

which is working perfectly but I need to run it after few seconds on getting into the page (with delay), so I used setTimeout() to get this but now the page jumps to the section (hash) without scrolling or prompting any error message.
setTimeout(function(){
  $('html,body').animate({
     scrollTop: $(window.location.hash).offset().top
  },1000);
}, 2000);

can you please let me know what I am doing wrong and why this is not working with delay?!

A: Try with:
  $('html,body').delay( 2000 ).animate({
     scrollTop: $(window.location.hash).offset().top
  },1000);

Other option is:
window.setTimeout(function(){
      $('html,body').animate({
         scrollTop: $(window.location.hash).offset().top
      },1000);
});