Q:

How can I pass a state object to a continuation task?

I'm using the .NET 4.0 Task Parallel Library with C# (my first time using TPL)
I have a task A which I want to run to completion before firing off a bunch of other tasks (B,C,D, etc). I therefore want to create tasks B,C,D etc as continuations of task A.
However, I want to pass a 'state' object to task B, another state object to task C, etc.
I can pass a state object to task A by simply using a Task constructor overload that takes a state object, for example http://msdn.microsoft.com/en-us/library/dd783035.aspx describes this Task constructor overload:
Task(Action<Object>, Object, CancellationToken)

This works fine, and the second argument is my 'state' object.
I want to create a continuation task, e.g. for task B:
Task taskB = taskA.ContinueWith(/* args here*/)

However, I cannot see a ContinueWith() overload (see http://msdn.microsoft.com/en-us/library/dd235663.aspx) which allows me to pass a 'state' object to a continuation task. How can this be done?
Notes:

I do not have the 'state' object for taskB available at the time I create taskA
The 'state' object for taskB is not an output (return value) of taskA

For some context, what I am doing is creating taskB, taskC, etc. inside a couple of loops and so I am passing the value of the loop variables to taskB, taskC, etc. using a state object, in order to avoid the problem of always ending up with the final value of the loop variables in the tasks (the closure issue).

A:

The simplest approach would probably be to simply capture it in the Func<Task, TResult> you pass into ContinueWith. For example:
object taskBState = GetStateHere();
Task taskB = taskA.ContinueWith(task => RealContinuation(task, taskBState));

Personally I find it easier to capture state like that than getting the state passed in anyway.


Q:

Polar co-ordinates, Jordan form, Axler textbook

I am trying to solve this Linear algebra question but I am unsure on how to proceed and get stuck.
Define a three-dimensional ``Givens rotation'' in the 1-2 plane by
 $$M := \left( \begin{array}{ccc} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{array} \right). $$
Given an arbitrary $3 \times 3$ matrix $A$, find the angle $\theta$ that will produce a 0 in the $(3,1)$ entry of $M^{-1}AM$.
Solving I get the equation $a cos \theta + b sin \theta =0$ and I am unable to fix a $\theta$ after using polar coordinates for a and b. Any and all help is welcome.

A:

Well, if
$$A := \left( \begin{array}{ccc} a_{11} & a_{12} & a_{13} \\
a_{21} & a_{22} & a_{23} \\
a_{31} & a_{32} & a_{33} \end{array} \right). $$
And combining this with the fact that we have that
$$M^{-1} := \left( \begin{array}{ccc} \cos\theta & \sin\theta & 0 \\ -\sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{array} \right). $$
Then we only need to be concerned with the $(3,1)$ entry of $AM$, which works out to be
$$a_{31} \text{cos} (\theta) - a_{32} \text{sin}(\theta) $$
Setting this to zero, we see that:
$$\theta  = \text{tan}^{-1}\Big(\frac{a_{31}}{a_{32}}\Big)$$


Q:

Getting from a sub folder to the root failing

I am trying to include a header/footer with php's include_once. I did not have any trouble until I created a sub-folder called, "states". I tried to include include_once("header.php"); and it is failing. I know it is because it is not in the same directory, so I tried include_once("/header.php"); and that did not work. I also tried doing this:
include_once("header/states.php");
include_once("header/.php");
What am I doing wrong for this to not get to the correct directory? I am trying to organize a bunch of files and I want to do this the correct way, so any help appreciated.

A:

Use ./ to reference the current directory:
        include_once("./states/header.php");

That's assuming the file you are referencing from is in the directory shown. If it's in another directory ( like _notes ) then the directory one level up can be referenced by ../, thus:
        include_once("../states/header.php");


Q:

Java thread sends same data to multiple classes

Hello there wise community of Stack Overflow!
I have a rather simple question: Say we have Class A, B, and C. class A implements Runnable, and Class B starts the thread.
How can i receive the same data in class C, as i can in class B?

A:

here is your A (Arunnable)
import java.util.Date;
import java.util.ArrayList;
import java.util.Iterator;

public class Arunnable implements Runnable {
    ArrayList<Bmain> subscribers = new ArrayList<Bmain>();
    public void run() {
        try {
            for (;;) {
                Thread.sleep(1000);
                String message = String.format("Hi! from Arunnable, now is %d", (new Date()).getTime());
                Iterator<Bmain> iter = subscribers.iterator();
                while (iter.hasNext()) {
                    Bmain o = iter.next();
                    o.publish(message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void subscribe(Bmain o) {
        subscribers.add(o);
    }
}

here is your B (Bmain)
import java.util.concurrent.ArrayBlockingQueue;

public class Bmain {
    ArrayBlockingQueue<String> messageQueue;
    Bmain() {
        messageQueue = new ArrayBlockingQueue<String>(10 /* capacity */, true /* fair? */);
    }
    public void doit() {
        Arunnable ar = new Arunnable();
        Thread a = new Thread(ar);
        a.setDaemon(false);
        a.start();

        Thread b = new Thread(new Cworker(ar));
        b.setDaemon(false);
        b.start();

        ar.subscribe(this);
        loop("Bmain  ");
    }
    public static void main(String[] args) {
        (new Bmain()).doit();
    }
    public void publish(String msg) {
        try {
            messageQueue.put(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void loop(String who) {
        try {
            for (;;) {
                String s = messageQueue.take();
                System.out.printf("%s got [%s]\n", who, s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

and here is your C (Cworker)
public class Cworker extends Bmain implements Runnable {
    Arunnable a;
    Cworker(Arunnable a) {
        this.a = a;
        a.subscribe(this);
    }
    public void run() {
        loop("Cworker");
    }
}

here I got the following output
Cworker got [Hi! from Arunnable, now is 1386281579391]
Bmain   got [Hi! from Arunnable, now is 1386281579391]
Cworker got [Hi! from Arunnable, now is 1386281580396]
Bmain   got [Hi! from Arunnable, now is 1386281580396]
Cworker got [Hi! from Arunnable, now is 1386281581396]
Bmain   got [Hi! from Arunnable, now is 1386281581396]
Cworker got [Hi! from Arunnable, now is 1386281582397]
Bmain   got [Hi! from Arunnable, now is 1386281582397]
Cworker got [Hi! from Arunnable, now is 1386281583397]
Bmain   got [Hi! from Arunnable, now is 1386281583397]

hope this is what you want


Q:

About inner products, norms and metrics

Do these three kinds of vector spaces, those with an inner-product, those with a norm and those with a metric, are the same sets of vector spaces? At least for finite dimensional vector spaces all of these coincide?
It would be great to know finite dimensional counter-examples if they exist any and if anyone can link to some lecture notes explaining this point.

Like are there examples of inner product spaces which cannot have a metric or metric spaces which cannot have a norm or various other such possible conflicts between these 3 properties.

A:

Even in finite dimension, the converses are not true.
For instance, the $p$-norm ($p≠2$) on $\Bbb R^n$ doesn't come from an inner product. This can be proven by contradiction, using the parallelogram law or the polarization identity. The polarization identity
$$2 \|x\|^2+2\|y\|^2=\|x+y\|^2+\|x-y\|^2 \qquad \forall x,y \in V$$
 precisely gives a necessary and sufficient condition for a normed vector space $V$ to have an inner product that induces that norm.
The discrete metric on $\Bbb R$ doesn't come from a norm, because it takes only $0$ and $1$ as values.
If $d$ is a metric such that there is a norm $\|\cdot\|$ on $V$ with $d(x,y)=\|x-y\|, \; \forall x,y \in V$, then two necessary conditions are that
$$d(ax,0)=|a|d(x,0) \tag 1 $$
$$d(x,y)=d(x+z,y+z) \tag 2$$
 for every $x,y,z \in V$ and $a \in \Bbb R$.
Conversely, if the metric $d$ satisfies $(1)$ and $(2)$, then $\|x\|:=d(x,0)$ yields a norm on $V$.
You can also see this question.


Q:

Virtual Host directives on Server - should I change the .config files?

I am trying to set up OpenPhoto on my Mavericks Server.
The instructions for a locally hosted site is to add directives to the virtual host config files.
Am I supposed to edit that file (0000_80_local_site.config)? It is written to by the Server app so am I afraid to edit it.
Where should I add the directives?

A:

I am battling with this issue as well. The Apple way of doing this is to create a web app and a plist file. The documentation is scarce, but you can type "man webapp.plist" at the terminal for an explanation. There is also an example app in "/Library/Server/Web/Config/apache2/webapps/com.example.mywebapp.plist" BTW,
I am looking at "Mountain Lion Server" and not the Mavericks version, so I am not sure if they are the same.
edit to add: I was able to get mine working by following the example at http://webapps.itcs.umich.edu/cosign/index.php/Mountain_lion_server_install
example app:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"          "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>includeFiles</key>
<array>
             <string>/Library/Server/Web/Config/apache2/webapp_scripts/httpd_myinclude.conf</    string>
</array>
<key>launchKeys</key>
<array>
    <string>com.example.mywebapp</string>
</array>
<key>name</key>
<string>com.example.mywebapp</string>
<key>displayName</key>
<string>MyWebApp</string>
<key>proxies</key>
<dict>
    <key>/mywebapp</key>
    <dict>
        <key>keysAndValues</key>
        <string></string>
        <key>path</key>
        <string>/mywebapp</string>
        <key>urls</key>
        <array>
            <string>http://localhost:3000</string>
            <string>http://localhost:3001</string>
        </array>
    </dict>
</dict>
<key>requiredModuleNames</key>
<array>
    <string>mod_mystuff.so</string>
</array>
<key>requiredWebAppNames</key>
<array>
    <string>com.example.webapp.myotherwebapp</string>
</array>
<key>preflightCommand</key>
<string>/usr/local/bin/preflightmywebapp</string>
<key>startCommand</key>
<string>/usr/local/bin/startmywebapp</string>
<key>stopCommand</key>
<string>/usr/local/bin/stopmywebapp</string>
<key>installationIndicatorFilePath</key>
<string>/usr/local/bin/mywebapp</string>
<key>sslPolicy</key>
<integer>0</integer>

Looks like you would put your .conf file in "/Library/Server/Web/Config/apache2/webapp_scripts/httpd_myinclude.conf"


Q:

GetFACL/SetFACL from PHP

I need to manage directory permissions via ACL on a linux box from PHP where we have setup a Windows share and mounted it on the local linux box. I'm looking for a way to get and set permissions for the directory within a PHP class that I can then use to interface with the frontend. I found some work by subutux back in 2010 - but not sure about the execution:
function getfacl($f){
  //inital parsing
  $facl = shell_exec("getfacl $f");
  $facl_ = explode("\n",$facl);
  //print_r($facl_);
  foreach ($facl_ as $line){
    // Getting creator
    if (!preg_match("/^# file.*/",$line) && preg_match("/^#.*/",$line)){
    $facl_rule = explode(": ",$line);
    //print_r($facl_rule);
      if ($facl_rule[0] == "# owner"){
      $facl_output['owner'] = $facl_rule[1];
      } else if ($facl_rule[0] = "# group"){
      $facl_output['group'] = $facl_rule[1];
      }
  }
  return $facl_output;
}

So, I have a two questions:

Does the above get the job done for GetFACL and how would I go about running a SetFACL command?
Are there any other known libraries for working with linux ACL from PHP?

A:

Didn't receive any responses on this one. I eventually got it working so I thought I would post in case anyone else ran into similar issue.
What we ended up doing was created a shared mount on the linux box from the MS directory on the external sever. From there we have rights via a user to that mount. I then used the library phpseclib, specifically the ssh2 component and ran shell commands to retrieve and run the ACL.
For example, here is a view of the php for retrieving the getfacl:
set_include_path(get_include_path() . PATH_SEPARATOR . '../phpseclib');
include('Net/SSH2.php');

$ssh = new Net_SSH2('location');
if (!$ssh->login('user', 'pass')) {
   exit('Login Failed');
}

echo $ssh->exec('ssh shared_mount_user@shared_mount_domain getfacl -R /folder/folder/file);

I can run all of my directory commands in similar function such as setfacl, ls, rm, etc.
I can also retrieve and parse the getfacl into specific parts like so:
$facl = $ssh->exec('ssh shared_mount_user@shared_mount_domain getfacl /folder/folder');
$facl_ = explode("\n",$facl);
$users_array = array();
foreach ($facl_ as $line){
     if (!preg_match("/^# file.*/",$line) && preg_match("/^#.*/",$line)){
     $facl_rule = explode(": ",$line);
     if ($facl_rule[0] == "# owner"){
        $facl_output['owner'] = $facl_rule[1];
     } else if ($facl_rule[0] = "# group"){
        $facl_output['group'] = $facl_rule[1];
     }
  }
  if (!preg_match("/^#/",$line) && preg_match("/^user:/",$line)){
     $facl_user_rule = explode(":",$line);
     array_push($users_array,$facl_user_rule);
  }
}

In the end, I wrote a class that puts all of these into nice little instances so I can do something like echo $FileManager->get_contents_array($ssh, $location); that will simply run a ssh ls command and parse the hierarchy to display in a directory UI.
Hope this helps out someone.


Q:

Truncated tar.gz archieve after download by a self-coded download manager using socket

i try to code my own download manager using c and sockets, now somethings strange happens and I really cannot explain why.
So what I do is: I create sockets, connect to server, create and send a GET Request.
Everythings is fine so far. The download starts, when its finished, I search the byte(char) array for '\n\r\n' to get to the end of the header(one further for start of the message body).
From there on I write msg_size-(header_end+1) bytes to a file. the resulting file has exactly the same byte size as if I download the file regulary. But when I try to extract it, it errors on a "unexpected end of file", while the other version extracts just fine.
Does anybody maybe have a explanation for that, also i can provide code, Im just not sure
where the problem can be, so i was trying first to verbalize the problem.
I tried allready the "wb" and "w" flag.
also the server does not specify chunked transfare or compressed encoding.
It is http/1.1 though.
Thanks!
edit:
so this is the server Header:
HTTP/1.1 200 OK
Date: Mon, 20 May 2013 16:33:26 GMT
Server: Apache/2.2.9 (Debian)
Last-Modified: Sun, 17 Jan 2010 18:17:39 GMT
ETag: "3ba006-29b376-47d60407b56c0"
Accept-Ranges: bytes
Content-Length: 2732918
Content-Type: application/x-gzip

edit2;
and this is how i recieve and write the file:
    memset(file,0,file_size);
    arg[1]=recv(socketfd,file,file_size,0);
    int mstart=0;
    while(file[mstart]!='\n' ||file[mstart+1]!='\r'|| file[mstart+2]!='\n'){
       mstart++;
    }
    mstart+=3;
    fsize=file_size;
    int fsize=file_size-mstart;       //file_size from Response Header
    fwrite(&(file[mstart]),1,fsize,fd);
    fclose(fd)

ok, that makes a lot of sense, so i tried this now:
(edit) mistake in there but this also doesnt work:
  fd=fopen(file_name,"wb");
  memset(file,0,file_size);
  recv(socketfd,file,3,0);
  while(1==1){
    if(file[0]=='\n' ||file[1]=='\r'|| file[2]=='\n'){
      recv(socketfd,file,3,0);
    }else{
      break;
    }
  }
  arg[1]=recv(socketfd,file,file_size,MSG_WAITALL);
  fwrite(file,1,file_size,fd);
  fclose(fd);

but its still now wokring
Finally! this works know, thanks alot to you!
  fd=fopen(file_name,"w");
  memset(file,0,file_size);
  recv(socketfd,file,3,0);
  while(file[0]!='\n' ||file[1]!='\r'|| file[2]!='\n'){
      recv(socketfd,file,3,0);
  }
  arg[1]=recv(socketfd,file,file_size,MSG_WAITALL);
  fwrite(file,1,file_size,fd);
  fclose(fd);

A:

Your file reading logic doesn't quite work. You first need to read some fixed amount, and parse that fixed amount to find the end of the headers. Then you parse the headers to find the content length. Then any data you have already read past the end of headers gets written out as the first part of your file. The rest of the file is the content length minus what you have written. It is that many more bytes you have to read from the socket and write to the file.
Your problem is that you have not properly utilized the content length header (which you had extracted from a previous HEAD request). It indicates the size of the transfer following the headers, not the length of the entire response.
The reason the file appears to be the correct size is that you are writing out the correct number of bytes, but you are reading past the end of the bytes you read from the socket (since you have adjusted mstart forward past the end of headers).


Q:

Calculate 2d rotation of a wall in a picture given 4 edge points

I want to compute the rotation (angle alpha) between the wall and the camera. (see Figure 1) The camera takes a photo as pictured in "camera view", and I get the 4 edge points of the wall (in 2d (x,y) coodinates).
How can I compute alpha if I know that the wall has to be a 16:9 rectangle if not distorted?

A:

You can see below a top view of your wall, with $B$ and $C$ the midpoints of the vertical walls, projected onto the plane of view at $B'$ and $C'$. I'm assuming that line $VA$, joining the camera to the center of the wall, is perpendicular to $B'C'$.
Let $VA=d$ and $VA'=s$. You have $BM=AB\sin\alpha$ and $AM=AB\cos\alpha$. By similarity we then obtain:
$A'B':MB=(VA-AM):VA'$, whence:
$$
A'B'={s\sin\alpha\over d-AB\cos\alpha}AB
\quad\hbox{and, analogously:}\quad
A'C'={s\sin\alpha\over d+AC\cos\alpha}AC.
$$
Summing up these equalities we thus get:
$$
\tag{1}
B'C'={sd\sin\alpha\over d^2-a^2\cos^2\alpha}BC,
$$
where I set $a=AB=AC$.

If $DE$ (with midpoint $B$) and $FG$ (with midpoint $C$) are the vertical sides of the wall (see picture below), their projections on the plane of view can be computed in a similar way because we have for instance $DE:D'E'=VB:VB'=VM:VA'$, which gives:
$$
D'E'={s\over d-a\cos\alpha}DE
\quad\hbox{and, in a similar way:}\quad
F'G'={s\over d+a\cos\alpha}FG,
$$
so that
$$
\tag{2}
D'E'+F'G'={sd\over d^2-a^2\cos^2\alpha}(DE+FG).
$$

Dividing $(1)$ by $(2)$ we finally get:
$$
{B'C'\over D'E'+F'G'}=\sin\alpha{BC\over DE+FG}.
$$
As $DE/BC=FG/BC=9/16$, from the above relation we easily obtain
$$
\sin\alpha={9\over 8}{B'C'\over D'E'+F'G'}.
$$


Q:

Cheese and eggs on backpacking trips

I have taken some hard cheeses onto backpacking trips quite successfully without spoilage, but I have not dared taking more than I can eat in about 3 days. Eggs I have not dared to take. I am interested in how long people have gone in arid climates before their cheese/eggs became inedible. I don't mind sweaty cheese or even some mold, but I do not care much about food poisoning in the backcountry.

A:

Cheese:
Long time. Especially hard cheeses. You can just cut any mold off the edge that might creep up. Cheeses sealed in cheese wax (gouda) are a good bet.
I've had extra-sharp cheddar un-refrigerated in the AZ desert for 8+ days, in the rocky mountains for 15+ days with no issues (aside from sweat.)
Blocks last longer than a pile of shredded cheese.
Be smart. Keep an eye on it. If it smells foul, don't eat it.
Eggs:
With shells intact, raw eggs last surprisingly long.
In the Borneo rain forest (just below the equator = hot) we would get pallets of 300+ raw eggs shipped up to camp that we would store, un-refrigerated in the shade, for 30 days at a time. (This was after however long un-refrigerated in the truck, the shop, and the supply boat...)
Sure, there was some spoilage - but a very small percentage. Just crack them into a separate container first before tossing them in your dish.
Or use an old farmers test: put your raw eggs in a bucket of water, "If they sink, they're safe. If they float, they fail."
Other people suggest cracking the eggs into a sterilized lexan bottle (rinse with bleach first) and then freezing (or not). These reportedly last for several days. (<-I have not tried this).
As a distant last option -- they are doing some pretty decent things with powdered eggs these days...

Caveat: These are my personal experiences. I am sure there are some official FDA guidelines and other related official paranoia. Possibly even tails of death and disease from eating day old cheese. Fine. Follow those if you choose. Or step outside of commercial convention and open a world of gourmet back-country dining.
Related: How long does mayonnaise last unrefrigerated in the back-country?

A:

I've never tried it myself, but I met people trekking (sorry, tramping) in New Zealand who had pre-scrambled eggs with them, on the 5 day Heaphy track. They were cooked quite hard, and so could be easily carried in a freezer bag without worrying about breaking them, and then warmed up, or eaten as is.
It was only day 2, so perhaps they didn't expect to keep them for long, but I remember them looking a lot nicer than all dried nonsense I was eating at the time! I guess their shelf life would be down to the weather at the time.

A:

Personal anecdotal experience:
hard cheese:
lasts about a week in cool climate
boiled eggs:
lasts 3 (maybe up to 5 days) before they start to get weird
unboiled eggs:
I have never even thought of taking them backpacking, but I know they are safe for two weeks unrefrigerated. (This might be a joke to try to carry with you though?)
hummus:
about a week, unrefrigerated


Q:

CSS / jQuery change animation duration of a rotating element

I need to change the animation duration of a rotating wheel. This is working in every browser I have tried it on desktop, except Safari and all iOS browsers.
The classes are applied and removed from the element but the animation duration doesn't change after the first one is called. Any insight will be greatly appreciated.

let speed = 0;
$('.spinner').addClass(`rotate-${speed}`);

$('.speedUp').on('click', function() {
  if (speed <= 2) {
    $('.spinner').removeClass(`rotate-${speed}`);
    speed += 1;
    $('.spinner').addClass(`rotate-${speed}`);
  }
})

$('.speedDown').on('click', function() {
  if (speed >= 1) {
    $('.spinner').removeClass(`rotate-${speed}`);
    speed -= 1;
    $('.spinner').addClass(`rotate-${speed}`);
  }
})
body {
  text-align: center;
}

h2 {
  cursor: pointer;
  font-size: 36px;
}

div.spinner {
  width: 200px;
  height: 200px;
  border: 3px dashed;
  border-radius: 50%;
  margin: auto;
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.rotate-0 { animation: rotate 0s linear infinite; }
.rotate-1 { animation: rotate 4s linear infinite; }
.rotate-2 { animation: rotate 3s linear infinite; }
.rotate-3 { animation: rotate 2s linear infinite; }

+

-

A:

Safari is an idiot browser sometimes - You "need" to make it re-render the element by hiding is for a split second, and showing it again.
The below snippet should work fine in safari
EDIT. Now I say "Need", but there obviously might be workarounds, that I am not aware of..

let speed = 0;
$('.spinner').addClass(`rotate-${speed}`);

$('.speedUp').on('click', function() {
  $('.spinner').hide();
  if (speed <= 2) {
    $('.spinner').removeClass(`rotate-${speed}`);
    speed += 1;
    $('.spinner').addClass(`rotate-${speed}`);
  }
  setTimeout(function() {
        $('.spinner').show();
    }, 50);
})

$('.speedDown').on('click', function() {
  $('.spinner').hide();
  if (speed >= 1) {
    $('.spinner').removeClass(`rotate-${speed}`);
    speed -= 1;
    $('.spinner').addClass(`rotate-${speed}`);
  }
  setTimeout(function() {
        $('.spinner').show();
    }, 50);
})
body {
  text-align: center;
}

h2 {
  cursor: pointer;
  font-size: 36px;
}

div.spinner {
  width: 200px;
  height: 200px;
  border: 3px dashed;
  border-radius: 50%;
  margin: auto;
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
@-webkit-keyframes rotate {
    0%          { -webkit-transform:rotate(0deg); }
    100%        { -webkit-transform:rotate(360deg); }
}

@-moz-keyframes rotate {
    0%          { -moz-transform:rotate(0deg); }
    100%        { -moz-transform:rotate(360deg); }
}

.rotate-0 {
    -webkit-animation:rotate 0s infinite linear;
    -moz-animation:rotate 0s infinite linear;
    animation: rotate 0s linear infinite;
}
.rotate-1 {
    -webkit-animation:rotate 4s infinite linear;
    -moz-animation:rotate 4s infinite linear;
    animation: rotate 4s linear infinite;
}
.rotate-2 {
    -webkit-animation:rotate 3s infinite linear;
    -moz-animation:rotate 3s infinite linear;
    animation: rotate 3s linear infinite;
}
.rotate-3 {
    -webkit-animation:rotate 2s infinite linear;
    -moz-animation:rotate 2s infinite linear;
    animation: rotate 2s linear infinite;
}

+

-


Q:

Is there a proper variable to track how many times a loop has looped?

I'm pretty new to coding, so forgive me if this is super obvious.
When running a while loop, and I want to only run if for a certain amount of times. Ex (python):
question_var = 0
while True:
  if condition:
    question_var += 1
    continue
  print("Condition not met")

I want to know if there is a proper variable to use in place of question_var. Similar to how i is used to represent index in a for loop. I understand that this is not necessary, but I just want to learn how to do it right. I have been using a variable named rev
Here is the actual program I am trying to run:
rev = 0
while rev <= 10:
  new_file_name = "C# is bad ({}).txt".format(rev)
  with open(new_file_name, 'w') as tempfile:
    tempfile.write("C# is bad.\nPython is good.\n")
  rev += 1

its a gag I made for my friend who likes C#, but when I was making it I felt the the variable rev seemed unprofesional.

A:

using a while True loop is useful in some cases, but it is often not the most idiomatic use in python. As mentioned in the comments, you might find a for loop more appropriate:
for rev in range(0, 11):
  new_file_name = "C# is bad ({}).txt".format(rev)
  with open(new_file_name, 'w') as tempfile:
    tempfile.write("C# is bad.\nPython is good.\n")

Also, you don't really need to use format() here, you could change the second line to:
  new_file_name = f"C# is bad ({rev}).txt"


Q:

ADO.NET OracleCommandBuilder performance issue

I'm currently investigating some performance issues in a .NET/Oracle application.
I've run an oracle trace file and I have noticed that the following query is being called a lot and is using a lot of resources:
select ac.constraint_name key_name, acc.column_name key_col,1
from all_cons_columns acc, all_constraints ac
where acc.owner = ac.owner
and acc.constraint_name = ac.constraint_name
and acc.table_name = ac.table_name
and ac.constraint_type = 'P'
and ac.owner = user
and ac.table_name = :TableName
order by acc.constraint_name

I have determined that this query is not being called from the application code, could it be generated by ADO.NET? The application uses OracleCommandBuilders.

A:

Yes, I expect is is OracleCommandBuilders that is doing that: it is finding out which columns form the primary key for the given table.  It needs to do this (and other metadata selects) to generate SQL statements for your application.


Q:

How to get default Pages folder programmatically in Sharepoint 2013

Using C# in Sharepoint 2013 I can reach Pages folder using web.Folders["Pages"] or web.GetFolder("Pages")
Some of our SPWebs are in Turkish language. Whole interface is in Turkish including all default folders.
Problem is Pages becomes Sayfalar in Turkish. Other folder names also different but their internal names are in English so it's not a big deal but Pages internal name is also in Turkish Sayfalar.
This could be a problem in other languages too. Pages may become something else.
So is there a way to get default Pages folder programmatically in any language without using if..then..else

A:

Try the below code:
using (SPSite site = new SPSite(http://url))
{
    using (SPWeb web = site.OpenWeb())
    {
        foreach (SPList list in web.Lists)
        {
            if (list.BaseType == SPBaseType.DocumentLibrary)
            {

                SPDocumentLibrary docLibrary = (SPDocumentLibrary)list;
                if (docLibrary.BaseTemplate == (SPListTemplateType)850)

                    Console.WriteLine("Pages Library")

            }
        }
    }
}


Q:

UI doesn't get updated sometimes in Android

I am trying to populate data in UI fetched through REST service. The data comes up everytime but the UI doesn't get populated sometimes. The UI is kind of listing but listview is not being used. There's a ScrollView which has LinearLayout as its child and then row views are added to the linearlayout. There are times when UI just doesn't get updated even if the data is passed to it.
private void showData(List list) {
if(list != null && list.isEmpty()) {
    mNoData.setVisibility(View.VISIBLE);
} else {
    mNoData.setVisibility(View.GONE);

    final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.details_layout);

    findViewById(R.id.details_progress).setVisibility(View.GONE);

    linearLayout.removeAllViews();
    LayoutInflater layoutInflater = getLayoutInflater();
    View rowView = null;
    TextView txtName = null;
    Button buttonPlay = null;

    for (int i = 0; i < list.size(); i++) {
        rowView = layoutInflater.inflate(R.layout.row_view, null);
        txtName = (TextView) rowView.findViewById(R.id.row_view_name);
        buttonPlay = (Button) rowView.findViewById(R.id.row_view_button_play);
        final Item item = (Item) list.get(i);
        rowView.setTag(i) ;
        txtName.setText(item.getName());
        final RecentItem recentItem = RecentsManager.getInstance().getRecentItemFromRefID(item.getId());

        if (recentItem !=null) {
            buttonPlay.setText(getString("Resume"));
            buttonPlay.requestFocus();
        }

        buttonPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recentItem!=null) {
                    //do some action
                } else {
                    //do some action
                }

                finish();
            }
        });

        final int tag = (Integer) rowView.getTag() ;
        rowView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //do some action
            }
        }) ;

        txtName.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //do some action
            }
        });

        buttonPlay.setId(i);

        if(i < list.size())
            buttonPlay.setNextFocusDownId(i+1);

        linearLayout.addView(rowView);

        if (i == 0) {
            buttonPlay.requestFocus();
            buttonPlay.setNextFocusUpId(mButtonReminder.getId());

            if(mButtonReminder != null) {
                mButtonReminder.setNextFocusDownId(buttonPlay.getId());
            }
        } else {
            buttonPlay.setNextFocusUpId(i-1);
        }
    }
}
}

I have even checked the linearlayout children's count and the count is always equal to list size which means rows are also being added to it but it just doesn't show up on the UI.
What can be the issue?

A:

I was able to resolve the issue by doing certain changes as adding fillViewPort="true" for scrollview. Also, there was a background thread which was trying to update the UI because of which UI thread was breaking. This didn't resulted in a crash but the UI updation didn't happened. With these two changes it's working fine.


Q:

Getting an error when trying to assign a data controller to a UICollectionViewController in XCode

I've set up a LibraryDataController class that gets data from an sqlite database. This is its .h file:
#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface LibraryDataController : NSObject{
    sqlite3 *database;
}
@property (nonatomic) NSMutableArray *masterPhotoList;

-(NSInteger)listCount;
-(NSString*)objectInListAtIndex:(NSUInteger)index;
-(void)createEditableCopyOfDatabaseIfNeeded;
-(void)initializeDefaultList;
-(void)closeDatabase;
@end

I also have a library view that has a LibraryDataController member:
#import <UIKit/UIKit.h>

@class LibraryDataController;
@interface LibraryViewController : UICollectionViewController

@property (nonatomic, strong) LibraryDataController *dataController;

@end

My problem occurs on the app startup where I load information from the sqlite database into a data controller (The init function does this successfully). Then I try to assign the database to the library view. The library view is the second view on a tab bar, and the tab bar controller is the root view.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    UITabBarController *tabController = (UITabBarController *)self.window.rootViewController;
    LibraryViewController *libraryView = [[tabController viewControllers] objectAtIndex:1];
    LibraryDataController *aDataController = [[LibraryDataController alloc] init];

    libraryView.dataController = aDataController;

    return YES;
 }

The error comes from the libraryView.dataController = aDataController; line. Any ideas about what my problem is? I'm thinking it may have to do with the UICollectionView as I am very new to it. This code is almost identical to code I used successfully with a UITableView and I was under the impression the two views were very similar. Thanks for your help.

A:

The error message
[UICollectionViewController setDataController:]: unrecognized selector sent to instance 0x71a5170

shows that libraryView (which is the second view controller of the tab bar controller) is an instance of UICollectionViewController, and not LibraryViewController, as you expected.
The solution is to set the "Custom Class" of the view controller in the storyboard file to "LibraryViewController" (using the "Identity inspector).


Q:

How do I add a column with buttons in to a gridview in asp.net?

As my gridview is populating I want to add an extra column with some buttons in but I can't seem to figure out how, or what might be the best way. Can anyone get me started?

A:

Use a Template Column
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1"
    OnRowCommand="GridView1_OnRowCommand">
    <Columns>
        <asp:BoundField DataField="name" HeaderText="Name" />
        <asp:BoundField DataField="email" HeaderText="Email" />
        <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="SendMail"
                    Text="SendMail" CommandArgument='<%# Eval("id") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName != "SendMail") return;
    int id = Convert.ToInt32(e.CommandArgument);
    // do something
}


Q:

Tool for taking notes for source code (kind of a call graph+)

I'm looking for a tool that would help me read a large amount of C++ source code for a complex product and understand relationships between components and datatype and have those relationshipts diagrammed and noted. The way I see it work for me is, I would create a note (node in diagram) 'foo', then for each function that 'foo' calls that I'm interested in (major ones) I would create children of 'foo' diagram nodes in order in which they get called and I would have a possibility to annotate each 'node' with 'missing arg check?' or 'do we need a fat lock here? rw maybe?' or similar and maybe have those nodes dotted-line-refer to a datatype that it works with. So in my mind it's kind of a Visio with auto-placed and auto-connected nodes, with 2-3 different connections/arrows types and ways to arrange it on a page so that the call-graph grows in one direction (downwards).
Pointers to such a tool will be greatly appreciated and if you can suggest a better approach to the process itself, let me know, I'm being swamped with the amount of code I want to digest and it's the first time for me, so I'm new to this. Thanks!
Update. Here's what I think I want in terms how it would look like
.
The 'automatic' part of the tool is that it would re-arrage the nodes, so all of them are visible, auto-size the nodes, create links by clicks (say right-click for child node and left click for datatype reference) and so on.

A:

Turns out the answer to my question was - the latest Microsoft Visual Studio. MS VC 2012 contains this - http://msdn.microsoft.com/en-us/library/dd409453.aspx, which is exactly what I've been looking for.


Q:

Can this MySQL subquery be optimised?

I have two tables, news and news_views. Every time an article is viewed, the news id, IP address and date is recorded in news_views.
I'm using a query with a subquery to fetch the most viewed titles from news, by getting the total count of views in the last 24 hours for each one.
It works fine except that it takes between 5-10 seconds to run, presumably because there's hundreds of thousands of rows in news_views and it has to go through the entire table before it can finish. The query is as follows, is there any way at all it can be improved?
SELECT n.title
,      nv.views
FROM   news n
LEFT
JOIN   (
       SELECT news_id
       ,      count( DISTINCT ip ) AS views
       FROM   news_views
       WHERE  datetime >= SUBDATE(now(), INTERVAL 24 HOUR)
       GROUP
       BY     news_id
       ) AS nv
ON     nv.news_id = n.id
ORDER
BY     views DESC
LIMIT  15

A:

I don't think you need to calculate the count of views as a derived table:
SELECT n.id, n.title, count( DISTINCT nv.ip ) AS views
FROM   news n
LEFT JOIN news_views nv
ON nv.news_id = n.id
WHERE nv.datetime >= SUBDATE(now(), INTERVAL 24 HOUR)
GROUP BY n.id, n.title
ORDER BY views DESC LIMIT  15

The best advice here is to run these queries through EXPLAIN (or whatever mysql's equivalent is) to see what the query will actually do - index scans, table scans, estimated costs, etc. Avoid full table scans.


Q:

What is the chance of getting a Bob-omb or a Mr. Saturn instead of a Turnip?

I have seen Peach pull up a Mr. Saturn before, and I want to know the chances of that happening.
The Bob-omb I am referencing came from a Project-M Clip I saw, so it might have only been in Melee.

A:

This tip shows up at one of the loading screens on the Wii U version:

Peach: Vegetable – Rarely, Peach will pull up a Bob-omb or Mr. Saturn. How rarely? Well, you have a 1/250 chance of a Bob-omb and a 1/166 chance of a Mr. Saturn!

I remembered seeing the tip (but forgot the numbers), then spent a good time searching for a reliable source. Eventually found it here.


Q:

Is it possible to run "pm create-user Name" command programmatically?

I am able to create the multiple user profile on Jellybean using "pm create-user Name"  terminal command on Emulator, but I want to know is there any way so I can run the same command programmatically. I don’t want to open the terminal.

A:

When the Multiple User feature was first found in 4.1, I wrote an app to do just this. I've open sourced it here. You can find the code for running that command programmatically in TerminalUtils, but I'll put it in the answer as well.
public static void createUser(String name)
{
    Process p;
    try {
        p = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(p.getOutputStream());

        os.writeBytes("pm create-user \"" + name + "\"\n");
        os.writeBytes("exit\n");
        os.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

TerminalUtils also contains methods to remove and rename users.


Q:

Make white background transparent png matlab

I am trying to remove the white background on my png picture I get from a code I created. This is the picture I get:

I want to make the white background transparent, because I have several of those images that I want to combine using imfuse.
What I do is this (my picture is called 'A1.png'):
A1=imread('A1.png');
D=zeros(size(A1));
D(A1==255) =1;
imwrite(A1,'A11.png','alpha',D);

However I get an error like this
Error using writepng>parseInputs
(line 349)
The value of 'alpha' is invalid.
Expected input to be of size 829x600
when it is actually size 829x600x3.
829x600x3 uint8 is the size of A1. I understand I need to get rid of the x3 thing. But i don't know if it's when I save the pic or earlier in my code.
What do you guys think?

A:

You need simply create D with one less dimension. Here is the code
D = zeros( size(A(:,:,1)) );
D( all( A==255, 3 ) ) = 1;
imwrite(A,'A11.png','alpha',D);


Q:

How I can receive Class0 (flash) SMS in my app?

I wrote app for receive SMS messages (like this example: Android – Listen For Incoming SMS Messages)
Everything works fine, but I doesn't receiving class0 SMS (on screen with Ok button SMS). How I can do that?

A:

By definition, class 0 SMS shows onscreen immediately, and cannot be suppressed.


Q:

WebClient Does not automatically redirect

When logging the login process using Firebug i see that it is like this
POST //The normal post request
GET //Automatically made after the login
GET //Automatically made after the login
GET //Automatically made after the login

When making a post request using my code below it did not make the automatic GET requests that the browsers is doing.
MY WebClient Handler
using System;
using System.Net;

namespace Test
{
    class HttpHandler : WebClient
    {
        private CookieContainer _mContainer = new CookieContainer();

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = _mContainer;
            }
            return request;
        }

        protected override WebResponse GetWebResponse(WebRequest request)
        {
            var response = base.GetWebResponse(request);
            if (response is HttpWebResponse)
                _mContainer.Add((response as HttpWebResponse).Cookies);
            return response;
        }

        public void ClearCookies()
        {
            _mContainer = new CookieContainer();
        }
    }
}

Using Code
private static async Task<byte[]> LoginAsync(string username, string password)
{
    var postData = new NameValueCollection();
    var uri = new Uri(string.Format("http://{0}/", ServerName));

    postData.Add("name", username);
    postData.Add("password", password);

    return await HttpHandler.UploadValuesTaskAsync(uri, postData);
}

When trying to track the connection of my application it is only doing the POST Request and not the rest of GET requests. [THAT ARE MADE AUTOMATICALLY IN THE BROWSER]

A:

Try adding
request.AllowAutoRedirect = true;

right under the
var request = base.GetWebRequest(address);

It solved some similar problems for me, even though AllowAutoRedirect is supposed to be true by default.

A:

That shouldn't be surprising, given that HttpWebRequest is not a browser.  If you need to perform these redirects, then check the HttpWebResponse.StatusCode, and make another request if it's a redirect code in the 300's.  Note from the link under 10.3 Redirection 3xx:

This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. The action required MAY be carried out by the user agent without interaction with the user if and only if the method used in the second request is GET or HEAD. A client SHOULD detect infinite redirection loops, since such loops generate network traffic for each redirection.


Q:

Segmentation fault in C code function

struct Node {
    char gender;
    int turns_in_bathroom;
    struct Node *next;
};

struct Queue {
    struct Node *front, *back;
};

int QueueDeleteNext(Queue *myQueue, char value) {
Node *current_node, *previous_node;
previous_node = NULL;
int found = 0;
for (current_node = myQueue->front; current_node != NULL;
     previous_node = current_node, current_node = current_node->next) {
    if (current_node->gender == value) {
        if (previous_node == NULL) {
            myQueue->front = myQueue->back = NULL;
        }
        else {
            previous_node->next = current_node->next;
            if(previous_node->next == NULL){
                myQueue->back = previous_node;
            }
        }
        free(current_node);
        found = 1;
    }
}
return found;
}

I'm getting a segmentation fault on the line
if (current_node->gender == value) {

I cannot for the life of me figure out why. What's going on here?
Not to mention the code will run all the way through despite the fault error in my debugger. There are some bugs that I think may be related to this, though, and I want to make sure I've got all my bases covered.

A:

Apparently, the problem has been solved, but there are still problems with the code:

The condition (previous_node == NULL) tests whether the current node is the queue's head. In that case, the head must be dajusted instead ofthe previous node's next, but the code emties the whole queue without properly deleting possible trailing enodes.
When the last node in the queue is deleted, the queue's back should be updated, so that subsequent pushes can append to the end.

Finally, it looks a bit as if the intention of the OP was to delete all nodes with the corresponding value, because the execution didn't stop after the first deletion. So let's do that and return the number of deleted nodes:
int QueueDeleteNext(struct Queue *q, char value)
{
    struct Node *prev = NULL;
    struct Node *curr = q->front;
    int count = 0;

    while (curr) {
        if (curr->gender == value) {
            struct Node *nn = curr;

            if (prev == NULL) {
                q->front = curr->next;
            } else {
                prev->next = curr->next;
            }

            if (curr == q->back) q->back = prev;

            curr = curr->next;

            free(nn);
            count++;
        } else {
            prev = curr;
            curr = curr->next;
        }
    }

    return count;
}

The main loop is now a while loop that treats deleting and skipping a node differently. In bothcases, the next node is curr->next, but when a node is deleted, the prevnode stays the same! This code also preserves the back of the queue.
Another way to implement this is to use a pointer to node pointer instead to a prev pointer. This eliminates the need to distinguish between the head and other nodes. nd is the address of the queue's head at first and the address of the previous node's ´nextfield after that. The code updates the pointer that points to the current node viand`:
int QueueDeleteNext(struct Queue *q, char value)
{
    struct Node **nd = &q->front;
    int count = 0;

    q->back = NULL;

    while (*nd) {
        if ((*nd)->gender == value) {
            struct Node *nn = *nd;

            (*nd) = (*nd)->next;

            free(nn);
            count++;
        } else {
            q->back = *nd;
            nd = &(*nd)->next;
        }
    }

    return count;
}

This code can be extended to just delete the first node or the first _n_nodes.


Q:

Modular arithmetic and using in well-ordering principle

I need to prove the following, but I do not know how to go about it.
If $$   (*)\:\:\: x^{3} - y^{3}= 3^{n} $$
Then $$ x \equiv 0 (mod 3)  \:\: and \:\:\: y \equiv 0 (mod 3)$$
In addition, to prove that the equation above (*), there is no solution in $ N^{+} $ (in other words $ \quad 0\neq x,y\in \mathbb N $ ).
By using the Well-ordering principle, i.e. Any non-empty subset of N, the set of natural numbers has a minimum element.
Edit
I can use these facts: $$ \forall x\in \mathbb N^{+}  \:\:\: x^{3}  \equiv x (mod 3)$$
And also:
$$ \forall x,y\in \mathbb N^{+} , \:\:\: if \:\:\: x^{3} - y^{3}\equiv 0 (mod 3) \:\:\: \\Then \:\:\: x \equiv y (mod 3)  $$
Thanks

A:

Let $x$ and $y$ be positive integers such that $x^3-y^3=3^n$, where $n\ge 3$. We first show  that $3$ divides $x$ and $3$ divides $y$. Then later we use this to show that in fact there are no positive solutions.
In the OP, it is observed that $x\equiv y\pmod{3}$, so $x-y$ is divisible by $3$.  Now we use the fact that $x^3-y^3=(x-y)(x^2+xy+y^2)$.
Note that if $x$ and $y$ are positive and not both equal to $1$, it follows that $x^2+xy+y^2\gt 3$, and therefore $x^2+xy+y^2=3^k$ for some $k\ge 2$. Now from the fact that $9$ divides $(x-y)^2$ and the identity
$$(x^2+xy+y^2)-(x-y)^2=3xy$$
we conclude that $9$ divides $3xy$.  Thus $3$ divides $xy$. It follows that $3$ divides one of $x$ or $y$, and therefore since $x\equiv y\pmod{3}$, it divides both.

Now that we have the divisibility result, the rest follows by the least number principle, or equivalently by infinite descent.
It is easy to verify that there are no positive solutions with $n=0$, $n=1$, or $n=2$. Suppose that for some $n\ge 3$ there are positive solutions. Then there is a smallest $n\ge 3$ with this property. Let $x^3-y^3=3^n$. From our divisibility result, we have $x=3s$, $y=3t$ for some positive $s$ and $t$. But then $3^3s^3-3^3t^3=3^n$ and therefore $s^3-t^3=3^{n-3}$, contradicting the minimality of $n$.
Remark: It is not quite true that if $x$ and $y$ are integers such that $x^3-y^3$ is a power of $3$ then $3$ divides $x$ and $y$. There is the obvious example $x=1$, $y=0$. But there is also the more interesting example $x=2$, $y=-1$, for which we have $x^3-y^3=9$.


Q:

How to set the O_CLOEXEC when using std::ofstream

What is the c++ (std::ofstream) equivalent of:
int fd = open(fn,O_WRONLY|O_NDELAY|O_APPEND|O_CREAT|O_CLOEXEC,0600);

The application I would like to use this for will only run on newer versions of linux, therefor portability is not an issue.

A:

There is (likely) no portable way to do this. There are at least two options.
First option, obtain fd / attach fd

Obtain the file descriptor of the ofstream
Attach a file descriptor to the ofstream

There are lots of examples of "attaching a file descriptor", "getting file descriptor from fstream" etc. If you can find one that works, you're all set.
If you can do the first one, you can do a fcntl on the file.
/* not checking return values since I am lazy; *you* should check them */
flags = fcntl(fd, F_GETFD);
flags |= FD_CLOEXEC;
fcntl(fd, F_SETFD, flags)

If you can do the second one, you can simply obtain your descriptor via open and attach it.
Second option, obtain all open fds and set FD_CLOEXEC on them
This is less clean (but more likely to work). Open all the fstreams you don't want your children to inherit. Go to /proc/self/fd. For each fd set the FC_CLOEXEC flag.


Q:

Beginner error in my first app

I'm new in Android Studio programming and I coded my first (bigger) app. The app works fine when I start it in the debugger.
But when I connect my tablet and try to start my app there I immediately get the error
08-04 14:40:27.752 30433-30433/com.applications.ars.mynotizenundactivityapp E/AndroidRuntime: FATAL EXCEPTION: main                                                           Process: com.applications.ars.mynotizenundactivityapp, PID: 30433
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.applications.ars.mynotizenundactivityapp/com.applications.ars.mynotizenundactivityapp.DateiAuswahlActivity}: java.lang.NullPointerException: Attempt to get length of null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.applications.ars.mynotizenundactivityapp.DateiAuswahlActivity.onCreate(DateiAuswahlActivity.java:96)
at android.app.Activity.performCreate(Activity.java:6955)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

I googled the error and it seens that there is perhaps a problem with my  .xml at my layout.
This is my .xml-File:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.applications.ars.mynotizenundactivityapp.DateiAuswahlActivity">
    <ListView
        android:id="@+id/lv_myListView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:entries="@color/colorAccent"
        android:visibility="visible" />
</android.support.constraint.ConstraintLayout>

And this is my java-File:
package com.applications.ars.mynotizenundactivityapp;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

public class DateiAuswahlActivity<T> extends AppCompatActivity {

    String my_projektverzeichnis;
    String my_projektordnername = "ars_MyOrdner";
    ArrayList my_karteikastenListe = new ArrayList();
    ArrayList my_URLKarteikastenListe = new ArrayList();
    String my_URLKarteikaesten_longString;
    String [] URLKarteikastenArray;
    ListAdapter adapter;

    ListView lv;
    int stopper = 1;
    GetURLFolderContent my_getURLFolderContent = new GetURLFolderContent();

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_dateiauswahl, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_URL_Download) {
            Toast.makeText(DateiAuswahlActivity.this, "Karteikästen werden heruntergeladen", Toast.LENGTH_LONG).show();
            try {
                my_URLKarteikaesten_longString = my_getURLFolderContent.execute("http://www.meuchelmord.net/andy/Android/listFiles.php").get();
                stopper =1;
            } catch (InterruptedException e) {
                Toast.makeText(DateiAuswahlActivity.this, "Sorry, keine Internetverbindung", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            } catch (ExecutionException e) {
                Toast.makeText(DateiAuswahlActivity.this, "Sorry, keine Internetverbindung", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
            URLKarteikastenArray = my_URLKarteikaesten_longString.split("<br />");
            for (int i=0;i<URLKarteikastenArray.length-1;i++){
                my_URLKarteikastenListe.add(URLKarteikastenArray[i]);
            }

            for (int i=0;i<my_URLKarteikastenListe.size();i++){
                String my_tempurl = "http://www.meuchelmord.net/andy/Android/".concat(my_URLKarteikastenListe.get(i).toString());
                GetURLFile my_URLFile = new GetURLFile();
                my_URLFile.execute(my_tempurl,my_URLKarteikastenListe.get(i).toString());
                my_URLFile = null;
            }
            my_karteikastenListe = my_URLKarteikastenListe;
            for (int i=0;i<my_karteikastenListe.size();i++){
                my_karteikastenListe.set(i,my_karteikastenListe.get(i).toString().replace(".kartei",""));
            }
            adapter = new ArrayAdapter<T>(getApplicationContext(), android.R.layout.simple_list_item_1, my_karteikastenListe);
            //lv = (ListView)findViewById(R.id.lv_myListView);
            lv.setAdapter(adapter);

            stopper =1;
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datei_auswahl);

        my_projektverzeichnis = Environment.getExternalStorageDirectory() + "/" + my_projektordnername;
        File my_dateien_alle = new File(my_projektverzeichnis);
        File[] my_dateien_alle_Array = my_dateien_alle.listFiles();

        for(int i = 0; i<my_dateien_alle_Array.length;i++){
            if (my_dateien_alle_Array[i].getName().endsWith(".kartei") ){

                String my_tempname = my_dateien_alle_Array[i].toString().replace(".kartei","");
                String[] my_temparray = my_tempname.split("/");
                my_tempname = my_temparray[my_temparray.length-1];
                my_karteikastenListe.add(my_tempname);
            }
        }

        //List valueList = new ArrayList<String>();
        //for (int i = 0; i < 10; i++)
        //{
        //    valueList.add("value"+i);
        //}
        //ListAdapter adapter = new ArrayAdapter<T>(getApplicationContext(), android.R.layout.simple_list_item_1, my_karteikastenListe);
        adapter = new ArrayAdapter<T>(getApplicationContext(), android.R.layout.simple_list_item_1, my_karteikastenListe);
        lv = (ListView)findViewById(R.id.lv_myListView);
        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
                Intent intent = new Intent();
                intent.setClassName(getPackageName(), getPackageName()+".MainActivity");
                intent.putExtra("Karteikasten", lv.getAdapter().getItem(arg2).toString());
                startActivity(intent);
            }
            });
        stopper = 1;
    }
}

About my Tablet:
Samsung Galaxy TAB A
Android Version 7.0
Kernel-Version: 3.18.14-11316739
The configuration of my emulator where there is no problem:
Android 7.0 (Google APIs)
API 24
Is there anyone who can give me a tip where I can search for the problem?
I have no idea...
In hope of a reply,
Andy

A:

File my_dateien_alle = new File(my_projektverzeichnis); I'm guessing the directory isn't created so the next line File[] my_dateien_alle_Array = my_dateien_alle.listFiles(); is returning null
You may want something like this to create your directory if it does not exist:
File dir = new File(Environment.getExternalStorageDirectory() + "/dirname");
if (!dir.exists()) {
    folder.mkdir();
}


Q:

Mass invoices duplicate Odoo8

Is there anyway to duplicate, or create, a bunch of invoices with xml-rpc?
I try with the copy method of the Odoo ORMApi
invoices = call('account.invoice','search_read', [('type','ilike',"out_invoice")])

for invoice in invoices:
inv = invoice.copy()

How can I insert the new invoice int the db?

A:

Try erppeek, it's a python library that makes this much easier
client = erppeek.Client(SERVER, DATABASE, USERNAME, PASSWORD)
invoices=client.search('account.invoice',[('type','ilike',"out_invoice")])
for i in range(len(invoices)):
    client.copy('account.invoice',invoices[i-1])


Q:

eureka status ip instead of Desktop or localhost

I am working with Eureka Netflix and I have a little problem.
When the app register it self on eureka it register like DESKTOP....

And I want to be like http://IP:PORT
This is my server properties:
server.port=8761

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.instance.preferIpAddress=true
logging.level.com.netflix.eureka=OFF
logging.level.com.netflix.discovery=OFF

And this is the client:
spring:
 application:
  name: Test 2
 server:
port: 0
eureka:
 client:
  serviceUrl:
   defaultZone: ${EUREKA_URI:http://localhost:8761/eureka}
  instance:
    preferIpAddress: true

So I think it is some configuration problem but I don't know what.

A:

I found a better solution for me.
I changed the propertie file like this:
eureka config
eureka.name=eureka
eureka.port=8761
eureka.preferSameZone=false
eureka.shouldUseDns=false
eureka.serviceUrl.default=http://localhost:8761/eureka/v2/
eureka.shouldOnDemandUpdateStatusChange=true
eureka.instance.leaseRenewalIntervalInSeconds=1
eureka.instance.leaseExpirationDurationInSeconds=2
# set application host
server.address=1.1.1.1
#set application port
server.port=8080
#set application name
spring.application.name=application

#configuration to set the ip of host instead of the default localhost
eureka.instance.prefer-ip-address=true
eureka.instance.ip-address=${server.address}
eureka.instance.instance-id=${server.address}:${server.port}

Now in the end it will show on eureka like
1.1.1.1:8080

A:

The text displayed in the status column is the instance-id.
With the following configuration in the client:
eureka.instance.preferIpAddress=true
eureka.instance.instance-id=

you can force eureka dashboard to display the ip address in this column.
The property eureka.instance.preferIpAddressis just the address that is returned when you ask for the address of this instance. So if you don't set eureka.instance.instance-id to null, the instance-id still contains the hostname but the link you get to this instance is based on the ip instead of the host name.
Hope this helps


Q:

Operations between the same field of a content type

I feel like this is a very basic question, but after a couple of years it is the first time I need something like this and I cannot wrap my mind around the structure and get an idea of how to acomplish it.
Lets say I have a content type called "Fruit" where I store data in the fields "Name" (text), "Description" (text), "Price" (integer), "Date" (date).
In a view I'd like to select the fruit with names "Pear" and "Apple" with their respective prices for the dates inserted, but also make mathematical operations on the prices of the fruit (Like, "The price of apples was the 3/4 of the price of pears"). I cannot think of a way to do this since it is actually the same field, only grouped by some other field.
Any suggestions?

A:

Install views_php module. This module adds a field to the view and it also provides a few tokens. You can use the current row values. Note that you have to insert the main fields before the PHP field and exclude the Price field from display, Then the $results,$data,$row objects will give you the value of the row, Do the mathematical calculations and output the result.


Q:

Evaluating this complicated integral using complex analysis

I am trying to evaluate this integral:
$$\boxed{\int_{-\pi}^\pi\sin(2\cos\theta)\cos((2m+1)\theta)\,d\theta}$$
where $m\in\mathbb{N}$, using complex analysis methods.
What I have done is to find the residue of $\sin(z+\frac 1z)$:
Since $$\sin(z+\frac 1z)=\sum_{k=0}^\infty\frac{(-1)^k(z+z^{-1})^{2k+1}}{(2k+1)!}$$, and using the Binomial theorem, we have $$(z+z^{-1})^{2k+1}=\sum_{r=0}^{2k+1}{{2k+1}\choose r}z^{2k+1-2r}$$.
Combining these two facts we have that the residue (coefficient of $z^{-1}$) is:
$$\sum_{k=0}^\infty\frac{(-1)^k}{(2k+1)!}{{2k+1}\choose{k+1}}$$.
After this I am kind of stuck.
I am aware of the standard technique of substituting $\cos\theta=\frac{z+z^{-1}}{2}$, $d\theta=\frac{dz}{iz}$, etc, but I am not sure what to do with the $\cos((2m+1)\theta)$.
Thanks for any help.
By the way, if it helps, the answer I am supposed to get is $$\boxed{2\pi\sum_{k=m}^\infty\frac{(-1)^k}{(2k+1)!}{{2k+1}\choose {k-m}}}$$.
Update: Using David Holden's excellent hint, I proceded to find the residue of the integrand.
So the integral becomes $\frac{1}{2i}\int_C\sin(z+z^{-1})(z^{2m}+z^{-2m-2})\,dz$.
I find the residue of the integrand to be
$$\sum_{k=m}^\infty \frac{(-1)^k}{(2k+1)!}{{2k+1}\choose{k+m+1}}+\sum_{k=0}^\infty\frac{(-1)^k}{(2k+1)!}{{2k+1}\choose{k-m}}$$
I may have made a mistake along the way, I can't get to the final answer.

A:

Consider that $\cos{\left [ (2 m+1) \theta \right ]} = \operatorname{Re}{\left [e^{i (2 m+1) \theta}\right ]} $.  Then we consider the integral
$$-i \oint_{|z|=1} dz \, \sin{\left ( z+\frac1{z} \right )} z^{2 m}$$
which is equal to $i 2 \pi$ times the sum of the residues of the integrand at $z=0$.  To evaluate the residues and their sum, we Taylor expand the sine term to get, as the integrand,
$$-i \sum_{k=0}^{\infty} \frac{(-1)^k}{(2 k+1)!} \left ( z+\frac1{z} \right )^{2 k+1} z^{2 m} $$
The coefficient of $z^{-1}$ in the $k$th term of the expansion is the coefficient of the $k+m+1$th term.  (You can work this out for successive values of $m$.)  Thus, the integral is equal to
$$2 \pi \sum_{k=0}^{\infty} \frac{(-1)^k}{(2 k+1)!} \binom{2 k+1}{k+m+1} = 2 \pi \sum_{k=0}^{\infty} \frac{(-1)^k}{(k-m)! (k+m+1)!}$$
To evaluate the sum, note that the terms for $k \lt m$ are zero.  Then we can shift the index of the sum to get
$$ 2 \pi \sum_{k=m}^{\infty} \frac{(-1)^k}{(k-m)! (k+m+1)!} =  2 \pi (-1)^m \sum_{k=0}^{\infty} \frac{(-1)^k}{k! (k+2 m+1)!}$$
The latter sum is recognizable as a Bessel function evaluated at $z=2$.  Thus,

$$\int_{-\pi}^{\pi} d\theta \, \sin{(2 \cos{\theta})} \cos{\left [ (2 m+1) \theta \right ]} = 2 \pi (-1)^m J_{2 m+1}(2)$$


Q:

Probability of an event occurring within a smaller time interval if one knows the probability of occurrence over a larger time interval

The following threads are related to my question, but since I have minimal confidence around probability & math, I'm not sure how to interpret some of this and whether the answers apply to my situation (I think I'm dealing with a binomial process and most of the relevant material I've found describes Poisson processes):

What is the probability of an event happening in some interval given probability of it in x interval?
Probability of an event that has happened, to have happened in a specific time range?
Calculate probability of an event occurring exactly once in an arbitrarily selected year, given mean annual occurrences over a century

Suppose I take "samples" of the environment in hopes of detecting something. I have a model that tells me the probability an event will occur at least once sometime between 7:00am and 8:00am. Suppose this probability is 0.25, and is based on an hourly weather prediction -- so my predictive model is only good to the hour. However, I can only take samples in scheduled chunks of one minute. Assuming perfect detection, what's my probability of detecting the event of interest if I sample any SINGLE random minute out of the hour? What is my probability of detecting this event if I can randomly sample 2,3,4,5... or any N <= 60 minutes out of this hour?
I was thinking it would make sense for my problem to spread this 0.25 probability uniformly between the 60 minutes since I only have hourly resolution. So if I can only sample 1 minute out of the hour, probability of the event occurring at least once in THAT minute is 0.25*1/60. If I can sample 2 minutes out of the hour, total probability of the event occurring at least once during those minutes is 0.25*2/60. Three minutes would be 0.25*3/60 and so on.
Alternatively, I know it might be more conventional to say: 1-((1-0.25/60)^N) for calculating the probability of this event happening at least once across N sampled minutes, but this feels less intuitive for me within the context of a disconnect between the time scales.
Perhaps either approach is fine depending on the system assumptions. Regardless,  is it okay to divvy up that 0.25 hourly probability among the 60 minutes the way I have done, or does this violate something basic in probability theory?
(If it helps provide context, the events I'm trying to detect are bird songs! I don't care about rates (Poisson), I just care about presence or absence of singing in a given sampled minute.)

A:

Well, you should care about rates and Poisson processes! If the bird songs are independent of each other and of time, then you can assume a Poisson process with a stable rate of, say, $\lambda$ songs per hour. The Poisson distribution tells you that the probability of no song during one hour is
$$
P(X=0)={\lambda^0 e^{-\lambda}\over 0!}=e^{-\lambda}.
$$
If this probability is equal to .25 then you can deduce the rate $\lambda$ as follows:
$$
e^{-\lambda}=1/4 \rightarrow \lambda=-\ln(1/4)=\ln4\approx 1.38629
\text{ song per hour.}
$$
If you are interested in what happens over $x$ minutes, then the expected number of songs will be $x\ln4/60$ and the probability of detecting (i.e., at least one song over $t$ minutes) will be
$$
P(X\geq1)=1-P(X=0)=1-{(t\ln4/60)^0 e^{-t(\ln4)/60}\over 0!}=e^{-t(\ln4)/60}.
$$
For a 1-minute interval, this is
$$
1-e^{-(\ln4)/60}\approx 0.02284.
$$
and for a 90-minute interval
$$
1-e^{-90(\ln4)/60}\approx 0.875.
$$


Q:

Getting first onNext signal from list of Mono

Consider there are 3 functions that results in Mono<Int>s. I am trying to get the first result emitted by any of the Monos. Here's a test to describe what I am looking for:
fun main() {
  StepVerifier
    .create(firstElement())
    .expectSubscription()
    .expectNext(3)
    .expectComplete()
    .verify()
}

fun firstElement(): Mono<Int> = Flux.concat(_1(), _2(), _3(), _4()).next()

fun _1(): Mono<Int> = 1.toMono().delayElement(Duration.ofMillis(1000))
fun _2(): Mono<Int> = Mono.empty()
fun _3(): Mono<Int> = 3.toMono().delayElement(Duration.ofMillis(500))
fun _4(): Mono<Int> = Mono.error(RuntimeException())

The question is in firstElement(), how to result in 3 since it's the first to emit an element. But, as you can see, from any of the Monos:

It's possible that any of them could emit faster than the rest
It's possible that any of them could emit empty or onComplete()
It's possible that any of them could emit error or onError()

I have tried several operators:

Mono.zip {...} requires all of them to emit, because the return is Tuple<Int!>
Mono.first(...) and Flux.first(...).next() transmits onComplete() and/or onError()
Flux.concat(...) eliminates onComplete() and onError() but it's still sequentially subscribing based on the order of the given Publisher<T>s

A:

You could resume on error with empty Mono and merge your functions
private Mono<Integer> firstElement() {
    return Flux.merge(
            _1().onErrorResume(ignored -> Mono.empty()),
            _2().onErrorResume(ignored -> Mono.empty()),
            _3().onErrorResume(ignored -> Mono.empty()),
            _4().onErrorResume(ignored -> Mono.empty()))
            .next();
}


Q:

Where can I order pressed Ubuntu 12.04 64bit Desktop CDs with professional graphics?

Canonical have confirmed today they will be shipping 32-bit Desktop CDs of 12.04 from their store, with the product page just updated to reflect this.
I prefer 64-bit, I thought it was now the default offering based on several articles like this one(2buntu.com).
I want to order pressed CDs in 64-bit to hand out to people. They look professional, and I know from experience that people are more inclined to try Ubuntu from one of these over a generic CD that I make.
Who offers pressed 64-bit 12.04 Desktop CDs that look professional, like the 32-bit version Canonical offers?

A:

On-Disk.com does; here is their page for Ubuntu 12.04. I am sure there are others as well, but I have always had good experiences with on-disk.com.


Q:

Get editable sharepoint list items

I want to get all the items of SharePoint list, but not the default columns data.
Basically, I want all the editable SharePoint list items that are displayed to user.
How can i do that using CAML Query and C#?

A:

You can use this code snippet to determine if field is editable or not:
 public static bool IsFieldEditableInSP2010(SPField spField)
        {
            SPList spList = spField.ParentList;

            SPFieldLookup fldLookup = spField as SPFieldLookup;
            bool bCountRelated = fldLookup != null && fldLookup.CountRelated;
            bool bMcolLookup = fldLookup != null && fldLookup.IsDependentLookup &&
                                            fldLookup.LookupList != "Docs";

            SPFieldType t = spField.Type;
            if (t == SPFieldType.Computed ||
                t == SPFieldType.File ||
                t == SPFieldType.Recurrence ||
                t == SPFieldType.CrossProjectLink ||
                t == SPFieldType.AllDayEvent)
            {
                return false;
            }

            if (!spField.Reorderable &&
                !bCountRelated &&
                !(spField.ReadOnlyField && spField.Type == SPFieldType.User) &&
                !(bMcolLookup && !spField.Hidden) &&
                !spList.HasExternalDataSource)
            {
                return false;
            }

            if ((spField.ReadOnlyField && !bCountRelated && !bMcolLookup) ||
                spList.HasExternalDataSource)
            {
        if(spField.Type == SPFieldType.Calculated || spField.Type == SPFieldType.User)
            return true;

            }
            else
                return true;

            return false;
        }


Q:

Bundle update & install fail after OS X lion upgrade - Rails 3

I Just updated to OS X Lion, and now when I run bundle update and bundle install, they both fail for different reasons.
Bundle Install gives me this error:
Using friendly_id (3.2.1.1)
Installing json (1.5.3) with native extensions /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems/installer.rb:483:in `rescue in block in build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/.rvm/rubies/ruby-1.9.2-p0/bin/ruby extconf.rb
checking for re.h... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/.rvm/rubies/ruby-1.9.2-p0/bin/ruby
/.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:368:in `try_do': The complier failed to generate an executable file. (RuntimeError)
You have to install development tools first.
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:452:in `try_cpp'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:834:in `block in have_header'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:693:in `block in checking_for'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:280:in `block (2 levels) in postpone'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:254:in `open'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:280:in `block in postpone'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:254:in `open'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:276:in `postpone'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:692:in `checking_for'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/mkmf.rb:833:in `have_header'
    from extconf.rb:14:in `<main>'

Gem files will remain installed in /.rvm/gems/ruby-1.9.2-p0/gems/json-1.5.3 for inspection.
Results logged to /.rvm/gems/ruby-1.9.2-p0/gems/json-1.5.3/ext/json/ext/parser/gem_make.out
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems/installer.rb:486:in `block in build_extensions'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems/installer.rb:446:in `each'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems/installer.rb:446:in `build_extensions'
    from /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems/installer.rb:198:in `install'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/source.rb:95:in `install'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/installer.rb:55:in `block in run'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/spec_set.rb:12:in `block in each'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/spec_set.rb:12:in `each'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/spec_set.rb:12:in `each'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/installer.rb:44:in `run'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/installer.rb:8:in `install'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/cli.rb:225:in `install'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/vendor/thor.rb:246:in `dispatch'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/lib/bundler/vendor/thor/base.rb:389:in `start'
    from /.rvm/gems/ruby-1.9.2-p0/gems/bundler-1.0.7/bin/bundle:13:in `<top (required)>'
    from /.rvm/gems/ruby-1.9.2-p0/bin/bundle:19:in `load'
    from /.rvm/gems/ruby-1.9.2-p0/bin/bundle:19:in `<main>'

Bundle Update gives me this error:
Installing sqlite3 (1.3.4) with native extensions /.rvm/rubies/ruby-1.9.2-p0/lib/ruby/1.9.1/rubygems/installer.rb:483:in `rescue in block in build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/.rvm/rubies/ruby-1.9.2-p0/bin/ruby extconf.rb
checking for sqlite3.h... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

This is my Gemfile:
source 'http://rubygems.org'

gem 'rails'
gem 'rake', '~> 0.8.7'

gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'will_paginate', '3.0.pre2'

gem 'paperclip', :git => 'git://github.com/thoughtbot/paperclip.git'
gem 'mime-types', :require => 'mime/types'

gem 'rails3-generators'

gem 'devise',  '~> 1.1.3'
gem 'devise_invitable', '~> 0.3.4'

gem 'declarative_authorization', :git => 'git://github.com/stffn/declarative_authorization.git'

gem 'aasm'
gem 'braintree'
gem 'stripe'

#For voting
gem 'thumbs_up'

# For In-Place-Editing
gem 'best_in_place'

#For slugs for the plans
gem "friendly_id", "~> 3.2"

gem 'aws-s3'

group :development do
    # Server
    gem 'thin'
    #gem 'rspec-rails', '2.0.1'
    gem 'annotate-models', '1.0.4'
    #gem 'rails-erd'
    gem 'annotate'
    gem 'faker', '0.3.1'
    gem 'ruby_parser'
end

This is my Gemfile.lock
GIT
  remote: git://github.com/stffn/declarative_authorization.git
  revision: 792b1558dd79c5305dadade72e9eb458073de190
  specs:
    declarative_authorization (0.5.3)

GIT
  remote: git://github.com/thoughtbot/paperclip.git
  revision: cbba34c2b9abb112bb9bae269edb2c8ab01adf51
  specs:
    paperclip (2.3.10)
      activerecord (>= 2.3.0)
      activesupport (>= 2.3.2)
      cocaine (>= 0.0.2)

GEM
  remote: http://rubygems.org/
  specs:
    aasm (2.2.0)
    abstract (1.0.0)
    actionmailer (3.0.8)
      actionpack (= 3.0.8)
      mail (~> 2.2.19)
    actionpack (3.0.8)
      activemodel (= 3.0.8)
      activesupport (= 3.0.8)
      builder (~> 2.1.2)
      erubis (~> 2.6.6)
      i18n (~> 0.5.0)
      rack (~> 1.2.1)
      rack-mount (~> 0.6.14)
      rack-test (~> 0.5.7)
      tzinfo (~> 0.3.23)
    activemodel (3.0.8)
      activesupport (= 3.0.8)
      builder (~> 2.1.2)
      i18n (~> 0.5.0)
    activerecord (3.0.8)
      activemodel (= 3.0.8)
      activesupport (= 3.0.8)
      arel (~> 2.0.10)
      tzinfo (~> 0.3.23)
    activeresource (3.0.8)
      activemodel (= 3.0.8)
      activesupport (= 3.0.8)
    activesupport (3.0.8)
    annotate (2.4.0)
    annotate-models (1.0.4)
    arel (2.0.10)
    aws-s3 (0.6.2)
      builder
      mime-types
      xml-simple
    babosa (0.3.5)
    bcrypt-ruby (2.1.4)
    bcrypt-ruby (2.1.4-x86-mingw32)
    best_in_place (0.1.9)
      rails (~> 3.0.0)
    braintree (2.10.1)
      builder (>= 2.0.0)
    builder (2.1.2)
    cocaine (0.1.0)
    daemons (1.1.3)
    devise (1.1.9)
      bcrypt-ruby (~> 2.1.2)
      warden (~> 1.0.2)
    devise_invitable (0.3.7)
      devise (~> 1.1.0)
    erubis (2.6.6)
      abstract (>= 1.0.0)
    eventmachine (0.12.10)
    faker (0.3.1)
    friendly_id (3.2.1.1)
      babosa (~> 0.3.0)
    i18n (0.5.0)
    json (1.5.3)
    mail (2.2.19)
      activesupport (>= 2.3.6)
      i18n (>= 0.4.0)
      mime-types (~> 1.16)
      treetop (~> 1.4.8)
    mime-types (1.16)
    polyglot (0.3.1)
    rack (1.2.3)
    rack-mount (0.6.14)
      rack (>= 1.0.0)
    rack-test (0.5.7)
      rack (>= 1.0)
    rails (3.0.8)
      actionmailer (= 3.0.8)
      actionpack (= 3.0.8)
      activerecord (= 3.0.8)
      activeresource (= 3.0.8)
      activesupport (= 3.0.8)
      bundler (~> 1.0)
      railties (= 3.0.8)
    rails3-generators (0.17.4)
      railties (>= 3.0.0)
    railties (3.0.8)
      actionpack (= 3.0.8)
      activesupport (= 3.0.8)
      rake (>= 0.8.7)
      thor (~> 0.14.4)
    rake (0.8.7)
    rest-client (1.6.1)
      mime-types (>= 1.16)
    ruby_parser (2.0.6)
      sexp_processor (~> 3.0)
    sexp_processor (3.0.5)
    sqlite3 (1.3.3)
    sqlite3 (1.3.3-x86-mingw32)
    sqlite3-ruby (1.3.3)
      sqlite3 (>= 1.3.3)
    stripe (1.5.3)
      json
      rest-client
    thin (1.2.11)
      daemons (>= 1.0.9)
      eventmachine (>= 0.12.6)
      rack (>= 1.0.0)
    thin (1.2.11-x86-mingw32)
      daemons (>= 1.0.9)
      eventmachine (>= 0.12.6)
      rack (>= 1.0.0)
    thor (0.14.6)
    thumbs_up (0.4.1)
    treetop (1.4.9)
      polyglot (>= 0.3.1)
    tzinfo (0.3.27)
    warden (1.0.4)
      rack (>= 1.0)
    will_paginate (3.0.pre2)
    xml-simple (1.0.16)

PLATFORMS
  ruby
  x86-mingw32

DEPENDENCIES
  aasm
  annotate
  annotate-models (= 1.0.4)
  aws-s3
  best_in_place
  braintree
  declarative_authorization!
  devise (~> 1.1.3)
  devise_invitable (~> 0.3.4)
  faker (= 0.3.1)
  friendly_id (~> 3.2)
  mime-types
  paperclip!
  rails
  rails3-generators
  rake (~> 0.8.7)
  ruby_parser
  sqlite3-ruby
  stripe
  thin
  thumbs_up
  will_paginate (= 3.0.pre2)

Running ruby 1.9.2p0
Lemme know if you need anything else.

A:

Make sure to install XCode. Install it from the App Store, but also run "Install Xcode" from the Applications folder.

A:

I had this problem, but XCode was installed. Turned out that I installed ruby-2.0.0 before XCode (it was a new laptop I was getting up to speed). Doing a:
rvm reinstall 2.0.0

Solved the problem for me.

A:

I had a similar error because I hadn't accepted the Xcode terms of service from the latest download.
sudo gcc --version
And then accept the agreement.


Q:

I cannot get the Klaxon dependency in Intellij to register

I for the life of me cannot seem to get the Klaxon dependency to work in Intellij. Other dependencies I have added (like gson) have worked fine. I have tried refreshing Gradle, tried a different version, etc. Nothing seems to be working so I can use the library. I could be missing something obvious (new to Gradle and Kotlin). Any help or suggestions would be greatly appreciated.
Gradle Script:
plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.3.11'
}

version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8",
            "com.beust:klaxon:5.0.5"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Import Won't Register
https://github.com/cbeust/klaxon

A:

So where are you getting this download from? Is it from below?
https://mvnrepository.com/artifact/com.beust/klaxon/5.0.5
If so, you need to add the jcenter() repo, like so:
repositories {
    mavenCentral()
    jcenter()
}

I saw it because in the above link, it says that the repo is from Jcenter. I also tried searching the mavenCentral repo and couldn't find the klaxon directory.
http://central.maven.org/maven2/com/beust/
If this isn't an issue, try refreshing your dependencies through Gradle like so:
(from proj dir) $ gradle clean
(from proj dir) $ gradle --refresh-dependencies


Q:

Identify me - (An easy riddle)

I am a South Korean car model named after a United States city which in turn is named in Spanish. Identify me.
It is a quick and easy riddle. I am sharing it just for fun.

A:

It could also be the

 Hyundai Santa FeHyundai is a south korean manufacturer, Santa Fe is the capital of New Mexico, and "Santa Fe" is Spanish and means "holy faith" in English.

A:

You are the

Hyundai Tucson (named after Tucson, Arizona)


Q:

Did Heimdall sacrifice himself for Hulk?

Firstly, it's not wrong to say that in Avengers: Infinity War Thanos and Black order may know how to bypass Heimdall's senses, provided that planetary-level Joutens can do it and even Dark elves INCLUDING their ships, so why not UNIVERSAL-level Thanos, his black order and his ship.
Secondly, Heimdall saw Thanos coming, and saw his resources like wielding a stone with space for more, and his black order.
Fearing for Thor and Hulk (fight with Thanos), Thanos may have killed Hulk on the spot, so he decides to transport Hulk to Earth knowing it will be for one last time knowing the consequences as he judged Hulk's life is more valuable.
So in both cases, Hulk's beating was inevitable, so did  Heimdall sacrifice himself for Hulk?

A:

Heimdall sacrifice himself?

In a sense...but he's doomed anyway.

... for the Hulk

Not directly.
From the action, it's clear that the Black Order is killing the wounded anyway so Heimdall is doomed regardless, especially since the ship is destroyed afterwards.
What he is clearly doing is sending information back to Earth the quickest and simplest way possible... by sending someone who was there and can tell the story of Thanos and his intentions.
His only other choices would seem to be Thor (who is imprisoned in metal) so it's not clear even if he could send Thor in that condition, and Loki...and he knows that Loki is untrustworthy.
So he sends the Hulk...or rather Hulk/Banner directly to Dr Strange.


Q:

How to use Java API's?

Probably really simple but I just cannot work out how to use any API's with Java (Using Eclipse).
Where do they go?
For example I want to use a Twitter API and I import it using:
import net.unto.twitter.Api;

I then include the API file in the same dictionary as my class file. (This is what I do in python)
Anyone care to tell me the simple answer?

A:

Typically APIs are packaged in so-called JARs, which stands for Java ARchive.  What you should do is:

Download the jar.
Put it in some sort of 'lib' directory in your project structure.  Do not put it with your source code.
Add the jar to your classpath.  Some IDEs you have to add jar by jar, others  you tell the IDE which directories are library directories and it will modify the classpath for you to include all the jars in the directory.
Import the relevant package in your files where you use the API.

Once you have the jar added to your classpath and import the relevant classes, Eclipse should automatically pick it up and allow you to use autocomplete features against the API.
It is also a good idea to get the source jar for any libraries you download.  Most IDEs let you attach src jars, so you can click into the API and see how the code is written.

A:

You need to include any external JARs in the build path.  In eclipse right click on the project and go to 'Build Path' > 'Configure Build Path' then go to the 'Libraries' tab and 'Add JARs'.  Also, when using eclipse it is easier not to maintain the import statements yourself, but instead use 'Organize Imports' (ctrl + shft + o) or Import the selected object (ctrl + shft + m).  If a matching object is available in the classpath it will be imported.

A:

Java APIs are distributed in JAR files (which are just zip files with a specifiec directory structure).
Download the jar in question, put it in a known location on your disk (known location as in, pay attention to the name of the direcctory where you store the downloaded jar).
There are two times you will need to reference a Jar file:

During project compilation.  This includes development of the project using an IDE like eclipse (they all compile the code to find errors).

Option 1, add an external jar:

Open the project properties in Eclipse
Select Java Build Path
Select the Libraries tab
Click the Add External Jar button
Browse to the location of the JAR in question.
Select the JAR.
Click the Open button.

Option 2, add the JAR to your web project's WEB-INF/lib directory.

During project execution.  This will be after you deploy your application to a web container (perhaps tomcat).  Store the JAR in question in the classpath of the appliction post deploy.  For simple web applications, you can put the jar in the project WEB-INF/lib directory.


Q:

After using a storyboard segue the Tab bar is not showing

There are some similar questions but not exactly the same, and some are quite old.
Basically the tab bar is going missing after I'm doing a performSegue on a button press.
The view controllers are laid out in the storyboard but I'm putting the text and buttons into them programatically.
Segues 1 & 2 are storyboard segues which are the kind "Present Modally". In the top right view controller when one of the buttons are pressed it sets a variable and performs Segue 2. This is where the Tab Bar is not visible.
Segue 3 is a relationship segue and you can see when it's selected (1st image) it shows the Tab Bar on "Second View". But in the 2nd image it shows segue 2 selected and the Tab Bar is missing.
I'm calling segue 2 like this:
performSegue(withIdentifier: "ShowChapter", sender: self)
Based on what I've read I think perhaps I need a Navigation Controller somewhere. Currently I have no navigation controllers so to test my code I have to Stop execution and start again.
If anyone can tell me how to have the Tab bar showing after segue 2 it would be much appreciated.

A:

Adobels solution is on the right track, I tried it, but it didn't work.
In the end what did the trick was a button on the top right View Controller which did a self.dismiss and then changed the tabbarcontroller selected index.
Here is the function called by a button. (chapter selection button)
@objc func selectChapter(button: UIButton) {
    CurrentChapter = button.tag
    self.dismiss(animated: false, completion: nil)
    if let tabBarController = self.presentingViewController as UITabBarController {
        tabBarController.selectedIndex = 1
    }
}


Q:

If value is greater than, less than and becomes greater than again

I'm having a problem with my following logic.
Jsfiddle
The logic
var budgetCalc = function (financeBudget, totalCost, remainingBudget, changeOn) {
    var reloadCalc = function () {
        var formula = parseFloat($(financeBudget).val()) - parseFloat($(totalCost).val());
        $(remainingBudget).val(Math.abs(formula.toFixed(0)));

        if ( formula >= 0 ) {
            $('.toolbar-budget').addClass('is-positive').append('
Remaining
');
        } else {
            $('.toolbar-budget').addClass('is-negative').append('
Over Budget
');
        }
    };

    $(document).ready(function () {
        // Price Input
        $(changeOn).change(function () {
           reloadCalc();
        });
        $(changeOn).trigger('change');
    });
};

What works fine
The interface has multiple selects, inputs and a jQuery sliders that change the value of formula. The logic works fine when the page loads and the formula value is >= 0. If the value is < 0 than the formula works fine as well.
The Issue
If the value of the formula is < 0 and then becomes > 0 again because the user changes the values contributing to formula, the logic does not change the class back to .is-positive unless the page refreshes.
My goal
I want the class of .is-positive to be applied without the page refreshing if the value goes from < 0 to >= 0.

A:

Seems like the simplest solution would be to remove both classes before adding the appropriate one but adding $('.toolbar-budget').removeClass('is-positive is-negative'); before your check:
$('.toolbar-budget').removeClass('is-positive is-negative');
if (formula >= 0) {
    $('.toolbar-budget').addClass('is-positive').append('
Remaining
');
} else {
    $('.toolbar-budget').addClass('is-negative').append('
Over Budget
');
}

jsFiddle example


Q:

Indentify old LEGO kit, classic car with bird driver

I have 2 parts left from a kit I had as a kid. I'm trying to find out what the kit was? I'm ALMOST sure the driver was a pose-able bird man, many thanks!

A:

Looks like it could come from one of two Fabuland sets, Bonnie Bunny's Camper or Charlie Crow's Carry-All. The radiator piece also comes in The Fabuland House.
Given your bird man as driver, I'm going with Charlie Crow's Carry-All.


Q:

Can't access members of a Template base class within a derived template class

I have a template base class.Lets say.
template<class KeyF>
class Base
{
  private:
   int member1;
   char member2;
   ....
};

I derived another class from above class.
template<class KeyF>
class Derived : public Base<KeyF>
{
  public:
  void func1() {
    <accessing member1/member2>
  }

  ....
};

Above code doesn't compile in gcc. saying that member1 is not a member of Derived. But it is already derived from a Base Class, then why can't it access its member?

A:

Members in Base are private. You cannot access private members of class, outside of this class (except friend). Make them protected, or make protected getters.