Null vs. False vs. 0 in PHP

Question: I am told that good developers can spot/utilize the difference between Null and False and 0 and all the other good "nothing" entities.
What is the difference, specifically in PHP?  Does it have something to do with ===?
Comment: It's almost impossible to actually really figure out when what is used. I guess it's important that you're CONSISTENT when you use `null` and when `false`. I prefer using `null` when retrieving a value from a method, because I can use `isset` to determine whether a value is returned instead of using `empty` which will not take in account: `false`, `0`, `'0'` or an empty string, which can be viable values in many situations. To me it's the cleanest solution in a messy construct.
Comment: As per @gcb comment https://stackoverflow.com/questions/137487/null-vs-false-vs-0-in-php#comment6514487_138954 triple equal strictly distinct one from the other where double don't. By default, use triple unless you explitely want 0 to be considered as Null or false (or the other way)
Answer: It's language specific, but in PHP :
Null means "nothing". The var has not been initialized.
False means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.
0 is an int. Nothing to do with the rest above, used for mathematics.
Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context, which (in PHP) is False.
If you test it with ==, it's testing the boolean value, so you will get equality. If you test it with ===, it will test the type, and you will get inequality.
So why are they useful ?
Well, look at the strrpos() function. It returns False if it did not find anything, but 0 if it has found something at the beginning of the string!
<?php
// pitfall :
if (strrpos("Hello World", "Hello")) {
    // never exectuted
}

// smart move :
if (strrpos("Hello World", "Hello") !== False) {
    // that works !
}
?>

And of course, if you deal with states, you want to make a difference between the following:

DebugMode = False (set to off)
DebugMode = True (set to on)
DebugMode = Null (not set at all; will lead to hard debugging ;-))
Comment: Note about Null: PHP uses it as "no value" but this is not a good habit to get into.  In general, Null means "unknown value" which is different than "no value" or "uninitialized variable".  Nothing plus 1 is 1, while an unknown value plus one is an unknown value.  Just remember that any operator applied to null will (should) result in null, because any operation on an "unknown value" results in an unknown value.
Comment: keep in mind that this is all **intentions**. nothing to do with what happens in reality. in reality a function can return false for non existent values (e.g. strpos, input_filter) and null for failure (e.g. input_filter). so the answer is, use ===false and/or ===null, after reading that particular function documentation.
Comment: @Eli: where do you get the idea that Null means "unknown value" in general.  I can't think of any computer languages where this is true, nor does it mean that in English, at least not according to any definition I can find or have heard.  Maybe you know something I don't know?
Comment: @iconoclast - I'm taking it from the database world.  As I understand it, null is used as a placeholder for a data value that doesn't exist in the database or is unknown.  See http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html or http://en.wikipedia.org/wiki/Null_%28SQL%29.
Comment: Eli's not wrong. He is stating that semantically, when you use null, you signal other programmers that you don't know what's in there. It's undefined. While when you use 0, you signal that you know what's in there: an number. And here the number represent the absence of things. Remember that no matter how PHP threats values, values carry a meaning, values are a form of documentation.
Comment: @Eli - IMHO, `null` is different than `NotANumber`. Any attempt to operate on null should result in an exception. I think it is a design mistake that php allows such operations. (I think it is equally foolish that php doesn't throw an exception on `false + 1`, it is entirely possible for a language to be weakly typed, such as VB's automatic conversion between string and numeric values, while still recognizing situations that are programming errors. But that is more debatable. `null` should be a special case, and treated strictly. Otherwise, chaos.)
Comment: Yes, a subtle yet important precision indeed. Since PHP is weakly typed, I guess it makes sense it implicitly turns "null + 1" in 1.
Comment: It better to use isset before check values.
Comment: In a technical, and therefore every practical sense, null is 0. There is no difference in value between any of these. Their types are meta data which PHP will also compare with `===`. For `==`, PHP is acting correctly. Think of this as comparing an array with [_type_, _value_], e.g. `[null, 0]`, rather than just comparing [_value_], which would be `[0]`. (My main point is, Eli's comment is very wrong).
Comment: @Deji - I disagree very strongly with your notion that "null is 0". That should NOT be the case in ANY programming language, including weakly typed ones; they are fundamentally different concepts. Its *extremely* unfortunate that php chose to blur this; doing so was *not at all necessary*. Eli makes the fundamental observation: any attempt to operate on "null" should *not* yield a useable result. `if(null)` or `if(!null)` should be an error - it indicates programmer has no clue what is happening. Given good language design, If `null` gets through to code like that, it indicates a logic bug.
Comment: `null + 1` is 1 ... just sayin. null literally means nothing, not "zero", "unknown value", "not a number", it means nothing. If you have no apples, and you know not what an apple is, or have not possed an apple your value of apples is nothing. You have zero concept of apples and their genome or how to account for apples, or what purpose or properties an apple might poses. If I give you an apple you now have an apple, it no longer has a null value. If you consume , gift or I take back the apple you have zero apples. or 0.
Comment: Treating null as 0 is, roughly speaking, for coders and not for programmers. Some say: write your code as if the one that has to read and maintain it is a psychopath who knows where you live.
Answer: null is null. false is false. Sad but true.
there's not much consistency in PHP (though it is improving on latest releases, there's too much backward compatibility). Despite the design wishing some consistency (outlined in the selected answer here), it all get confusing when you consider method returns that use false/null in not-so-easy to reason ways.
You will often see null being used when they are already using false for something. e.g. filter_input(). They return false if the variable fails the filter, and null if the variable does not exists (does not existing means it also failed the filter?)
Methods returning false/null/string/etc interchangeably is a hack when the author care about the type of failure, for example, with filter_input() you can check for ===false or ===null if you care why the validation failed. But if you don't it might be a pitfall as one might forget to add the check for ===null if they only remembered to write the test case for ===false. And most php unit test/coverage tools will not call your attention for the missing, untested code path!
Lastly, here's some fun with type juggling. not even including arrays or objects.
var_dump( 0<0 );        #bool(false)
var_dump( 1<0 );        #bool(false)
var_dump( -1<0 );       #bool(true)
var_dump( false<0 );    #bool(false)
var_dump( null<0 );     #bool(false)
var_dump( ''<0 );       #bool(false)
var_dump( 'a'<0 );      #bool(false)
echo "\n";
var_dump( !0 );        #bool(true)
var_dump( !1 );        #bool(false)
var_dump( !-1 );       #bool(false)
var_dump( !false );    #bool(true)
var_dump( !null );     #bool(true)
var_dump( !'' );       #bool(true)
var_dump( !'a' );      #bool(false)
echo "\n";
var_dump( false == 0 );        #bool(true)
var_dump( false == 1 );        #bool(false)
var_dump( false == -1 );       #bool(false)
var_dump( false == false );    #bool(true)
var_dump( false == null );     #bool(true)
var_dump( false == '' );       #bool(true)
var_dump( false == 'a' );      #bool(false)
echo "\n";
var_dump( null == 0 );        #bool(true)
var_dump( null == 1 );        #bool(false)
var_dump( null == -1 );       #bool(false)
var_dump( null == false );    #bool(true)
var_dump( null == null );     #bool(true)
var_dump( null == '' );       #bool(true)
var_dump( null == 'a' );      #bool(false)
echo "\n";
$a=0; var_dump( empty($a) );        #bool(true)
$a=1; var_dump( empty($a) );        #bool(false)
$a=-1; var_dump( empty($a) );       #bool(false)
$a=false; var_dump( empty($a) );    #bool(true)
$a=null; var_dump( empty($a) );     #bool(true)
$a=''; var_dump( empty($a) );       #bool(true)
$a='a'; var_dump( empty($a));      # bool(false)
echo "\n"; #new block suggested by @thehpi
var_dump( null < -1 ); #bool(true)
var_dump( null < 0 ); #bool(false)
var_dump( null < 1 ); #bool(true)
var_dump( -1 > true ); #bool(false)
var_dump( 0 > true ); #bool(false)
var_dump( 1 > true ); #bool(true)
var_dump( -1 > false ); #bool(true)
var_dump( 0 > false ); #bool(false)
var_dump( 1 > true ); #bool(true)

Comment: in my opionion 0 == null is absolut nonsense, since 0 is a value and null is a flag that show the variable is uninitialized. Thanks php team
Comment: You twice repeated your section of code starting with `var_dump( null == 0 );`.
Comment: what is really weird in php : null < -1 => TRUE
Comment: @mercsen At the least if PHP consistently behaved like 0 == null I would have been OK with it. Oddly, `0 == null` and `null == []`, but `[] != 0` !!
Comment: `strrpos('fail', 'search') will return false, and not null` in my opinion is correct - if `null` means unknown then `strrpos` returning `null` would be like it saying 'I don't know if the string is there' rather than 'The string isn't there'.
Comment: This is more PHP-bashing (and partly incorrect), than an answer.
Comment: @mercsen It is better to say "unset" instead "uninitialized".
Comment: Some of the commented "values returned" are incorrect, dating back to PHP 5 versions. See https://3v4l.org/kYZnZ for up-to-date returned values for the above snippet (in many versions of PHP). Or paste in your own at: https://3v4l.org
Comment: the type jugling stuff was just a "for fun" after the actual answer. if you want to update with php7 saner (backward compatibility breaking?) results, feel free. i think everyone can edit/update answers here
Answer: Below is an example:
            Comparisons of $x with PHP functions

Expression          gettype()   empty()     is_null()   isset() boolean : if($x)
$x = "";            string      TRUE        FALSE       TRUE    FALSE
$x = null;          NULL        TRUE        TRUE        FALSE   FALSE
var $x;             NULL        TRUE        TRUE        FALSE   FALSE
$x is undefined     NULL        TRUE        TRUE        FALSE   FALSE
$x = array();       array       TRUE        FALSE       TRUE    FALSE
$x = false;         boolean     TRUE        FALSE       TRUE    FALSE
$x = true;          boolean     FALSE       FALSE       TRUE    TRUE
$x = 1;             integer     FALSE       FALSE       TRUE    TRUE
$x = 42;            integer     FALSE       FALSE       TRUE    TRUE
$x = 0;             integer     TRUE        FALSE       TRUE    FALSE
$x = -1;            integer     FALSE       FALSE       TRUE    TRUE
$x = "1";           string      FALSE       FALSE       TRUE    TRUE
$x = "0";           string      TRUE        FALSE       TRUE    FALSE
$x = "-1";          string      FALSE       FALSE       TRUE    TRUE
$x = "php";         string      FALSE       FALSE       TRUE    TRUE
$x = "true";        string      FALSE       FALSE       TRUE    TRUE
$x = "false";       string      FALSE       FALSE       TRUE    TRUE

Please see this for more reference of type comparisons in PHP. It should give you a clear understanding.
Answer: In PHP you can use === and !== operators to check not only if the values are equal but also if their types match. So for example: 0 == false is true, but 0 === false is false. The same goes for != versus !==. Also in case you compare null to the other two using the mentioned operators, expect similar results.
Now in PHP this quality of values is usually used when returning a value which sometimes can be 0 (zero), but sometimes it might be that the function failed. In such cases in PHP you return false and you have to check for these cases using the identity operator ===. For example if you are searching for a position of one string inside the other and you're using strpos(), this function will return the numeric position which can be 0 if the string is found at the very beginning, but if the string is not found at all, then strpos() will return false and you have to take this into account when dealing with the result.
If you will use the same technique in your functions, anybody familiar with the standard PHP library will understand what is going on and how to check if the returned value is what is wanted or did some error occur while processing. The same actually goes for function params, you can process them differently depending on if they are arrays or strings or what not, and this technique is used throughout PHP heavily too, so everybody will get it quite easily. So I guess that's the power.
Answer: False, Null, Nothing, 0, Undefined, etc., etc.
Each of these has specific meanings that correlate with actual concepts. Sometimes multiple meanings are overloaded into a single keyword or value.
In C and C++, NULL, False and 0 are overloaded to the same value.
In C# they're 3 distinct concepts.
null or NULL usually indicates a lack of value, but usually doesn't specify why.
0 indicates the natural number zero and has type-equivalence to 1, 2, 3, etc. and in languages that support separate concepts of NULL should be treated only a number.
False indicates non-truth. And it used in binary values. It doesn't mean unset, nor does it mean 0. It simply indicates one of two binary values.
Nothing can indicate that the value is specifically set to be nothing which indicates the same thing as null, but with intent.
Undefined in some languages indicates that the value has yet to be set because no code has specified an actual value.
Comment: Interesting, perhaps, but does not discuss PHP at all.
Answer: I have just wasted 1/2 a day trying to get either a 0, null, false to return from strops!
Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding:
Concept
take a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done.
Anyway here was the basis of the cosing:
if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ())
{
    do this
} else {
    or that
}

{
echo strpos(mydomain.co.uk, mydomain);

if ( strpos(mydomain, xmas) == null )
    {
        echo "\n1 is null";
    }

if ( (strpos(mydomain.co.uk, mydomain)) == 0 )
    {
        echo "\n2 is 0";
    } else {
        echo "\n2 Something is WRONG";
    }

if ( (mydomain.co.uk, mydomain)) != 0 )
    {
        echo "\n3 is 0";
    } else {
        echo "\n3 it is not 0";
    }

if ( (mydomain.co.uk, mydomain)) == null )
    {
        echo "\n4 is null";
    } else {
        echo "\n4 Something is WRONG";
    }
}

FINALLY after reading this Topic,
I found that this worked!!!
{
if ((mydomain.co.uk, mydomain)) !== false )
    {
        echo "\n5 is True";
    } else {
        echo "\n5 is False";
    }
}

Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as false, as its also can be a NULL day!
After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as False, NULL and 0 are not all the same as True or False or NULL?
Answer: From the PHP online documentation:

To explicitly convert a value to boolean, use the (bool) or (boolean) casts.
However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
When converting to boolean, the following values are considered FALSE:

the boolean FALSE itself
the integer ``0 (zero)
the float 0.0 (zero)
the empty string, and the string "0"
an array with zero elements
an object with zero member variables (PHP 4 only)
the special type NULL (including unset variables)
SimpleXML objects created from empty tags
Every other value is considered TRUE (including any resource).

So, in most cases, it's the same.
On the other hand, the === and the ==are not the same thing. Regularly, you just need the "equals" operator. To clarify:
$a == $b    //Equal. TRUE if $a is equal to $b.
$a === $b   //Identical. TRUE if $a is equal to $b, and they are of the same type.

For more information, check the "Comparison Operators" page in the PHP online docs.
Hope this helps.
Answer: The differences between these values always come down to detailed language-specific rules. What you learn for PHP isn't necessarily true for Python, or Perl, or C, etc. While it is valuable to learn the rules for the language(s) you're working with, relying on them too much is asking for trouble. The trouble comes when the next programmer needs to maintain your code and you've used some construct that takes advantage of some little detail of Null vs. False (for example). Your code should look correct (and conversely, wrong code should look wrong).
Answer: Null is used in databases to represent "no record" or "no information". So you might have a bit field that describes "does this user want to be sent e-mails by us", where True means they do, False means they don't want to be sent anything, but Null would mean that you don't know. They can come about through outer joins and suchlike.
The logical implications of Null are often different - in some languages NULL is not equal to anything, so if(a == NULL) will always be false.
So personally I'd always initialise a boolean to FALSE, and initialising one to NULL would look a bit icky (even in C where the two are both just 0... just a style thing).
Answer: In PHP it depends on if you are validating types:
(
 ( false !== 0 ) && ( false !== -1 ) && ( false == 0 ) && ( false == -1 ) &&
 ( false !== null ) && ( false == null )
)

Technically null is 0x00 but in PHP ( null == 0x00 ) && ( null !== 0x00 ).
0 is an integer value.
Answer: I think bad developers find all different uses of null/0/false in there code.
For example, one of the most common mistakes developers make is to return error code in the form of data with a function.
// On error GetChar returns -1
int GetChar()

This is an example of a sugar interface. This is exsplained in the book "Debuging the software development proccess" and also in another book "writing correct code".
The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot.
Instead, the best way is not to mix error code with your data. So the following function.
char GetChar()

now becomes
// On success return 1
// on failure return 0
bool GetChar(int &char)

This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code.
So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine.
Answer: One interesting fact about NULL in PHP: If you set a var equal to NULL, it is the same as if you had called unset() on it.
NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0, "0", "", and false.
Answer: Null is nothing, False is a bit, and 0 is (probably) 32 bits.
Not a PHP expert, but in some of the more modern languages those aren't interchangeable.  I kind of miss having 0 and false be interchangeable, but with boolean being an actual type you can have methods and objects associated with it so that's just a tradeoff.  Null is null though, the absence of anything essentially.
Answer: Well, I can't remember enough from my PHP days to answer the "===" part, but for most C-style languages, NULL should be used in the context of pointer values, false as a boolean, and zero as a numeric value such as an int.  '\0' is the customary value for a character context.  I usually also prefer to use 0.0 for floats and doubles.
So.. the quick answer is: context.
Answer: In pretty much all modern languages, null logically refers to pointers (or references) not having a value, or a variable that is not initialized.  0 is the integer value of zero, and false is the boolean value of, well, false.  To make things complicated, in C, for example, null, 0, and false are all represented the exact same way.  I don't know how it works in PHP.
Then, to complicate things more, databases have a concept of null, which means missing or not applicable, and most languages don't have a direct way to map a DBNull to their null.  Until recently, for example, there was no distinction between an int being null and being zero, but that was changed with nullable ints.
Sorry to make this sound complicated.  It's just that this has been a harry sticking point in languages for years, and up until recently, it hasn't had any clear resolution anywhere.  People used to just kludge things together or make blank or 0 represent nulls in the database, which doesn't always work too well.
Answer: False and 0 are conceptually similar, i.e. they are isomorphic. 0 is the initial value for the algebra of natural numbers, and False is the initial value for the Boolean algebra.
In other words, 0 can be defined as the number which, when added to some natural number, yields that same number:
x + 0 = x

Similarly, False is a value such that a disjunction of it and any other value is that same value:
x || False = x

Null is conceptually something totally different. Depending on the language, there are different semantics for it, but none of them describe an "initial value" as False and 0 are. There is no algebra for Null. It pertains to variables, usually to denote that the variable has no specific value in the current context. In most languages, there are no operations defined on Null, and it's an error to use Null as an operand. In some languages, there is a special value called "bottom" rather than "null", which is a placeholder for the value of a computation that does not terminate.
I've written more extensively about the implications of NULL elsewhere.
Comment: offtopic, false == 0 is completely retarded. Even more so with php returning data OR failure in a function. see the return for mysql_insert_id. """The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.""" basically it can return A)the id, B)zero, C)false... now if that's the 1st item in the table, id will be zero! so all three values are the same! how can the developer make sense of three types of zeroes? ...and i agree with your post on null.
Answer: Somebody can explain to me why 'NULL' is not just a string in a comparison instance?
$x = 0;
var_dump($x == 'NULL');  # TRUE   !!!WTF!!!

Comment: Because PHP internally casts to the integer type and compares then. `php > var_dump((int) "NULL"); // => int(0)` `php > var_dump((int) "BLA"); // => int(0)` see php.net/manual/en/language.operators.comparison.php Translate strings and resources to numbers, usual math
Answer: The issues with falsyness comes from the PHP history. The problem targets the not well defined scalar type.
'*' == true -> true (string match)
'*' === true -> false (numberic match)

(int)'*' == true -> false
(string)'*' == true -> true

PHP7 strictness is a step forward, but maybe not enough.

Null vs. False vs. 0 in PHP


Getting blank SyntaxError on the last line

Question: I'm a beginner to programming, and i'm trying to write this twitter bot using Twython as an exercise to learn Python. I've started getting this SyntaxError on the last line:
     ~/tweetbot $ python tweet_test.py
File "tweet_test.py", line 32

               ^
SyntaxError: invalid syntax

I've searched for the problem, and it seems to normally be related either to leaving parenthesis open, or Python expecting some more code. I tried different things I found, like ending with sys.exit(), but I seem to always get the SyntaxError.
Here is the code:
import sys
from twython import Twython, TwythonError

apiKey = 'letters and numbers'
apiSecret = 'letters and numbers'
accessToken = 'letters and numbers'
accessTokenSecret = 'letters and numbers'

twitter = Twython(apiKey, apiSecret, accessToken, accessTokenSecret)

try:
    searchResult = twitter.search(q='searchTerm',lang='es',result_type='recent',count='3')
    for tweet in searchResult['statuses']:
        tweeted = open('answered').readlines()
        if tweet['id_str'] in tweeted:
            print '1 tweet is already answered'
        else:
            print 'Tweet from @%s Date: %s' % (tweet['user']['screen_name'].encode('utf-8'), tweet['created_at'])
            print tweet['text'].encode('utf-8'), '\n'

            twitter.update_status(status=message, in_reply_to_status_id=tweet['id_str'])
            message = 'tweetReply'
            print "Tweeted: " + message

            answeredTweet = '"' + tweet['id_str'] + '"\n'
            f = open('answered', 'w')
            f.write(answeredTweet)

Answer: You never provide an except: or finally: block for your try: statement. It is not optional.
If you didn't actually want to use an exception handler, just remove the try: and un-indent the whole block.
Comment: Thank you, this has fixed the problem.


How can I change the putting camera angle?

Question: I have been playing around with the visual presentation settings to my personal preference... but I can't seem to change the camera view that is shown when I put the ball ( the action of the ball rolling to the hole ).  The camera seems to be random but from my experiences, the camera angle is shown from where the fans are standing (next to the green) - which IMHO ruins the intense/thrilling part of the putt.
How can I change this angle to be shown of more from an eagle's eye or above the ball view ?
I will try to post a picture of what I am talking about soon.
Answer: Click the left analog stick when not in approach shot view.


How to get the old value in a select without unchecked with option formed with an foreach

Question: I need a little help..
In case of validation errors, when the page is reloaded I lose the information entered previously.
This is my code:
Controller:
public function create()
    {
        $nationalities = array('Italian','Brazilian','Spanish','Romanian');
        return view('guest.create', ['nationalities'=>$nationalities);
    }

public function store(Request $request)
    {
        $request->validate([
            'nationality' => 'required'
        ]);

        Guest::create([
            'nationality' => $request->nationality
        ]);

        return redirect(route('guest.index'));
    }

View:

    Select*
    <select class="form-select" id="nationality" name="nationality" aria-label="Floating label select example">
        @foreach($nationalities as $nationality)
        <option value="{{$nationality}}">{{$nationality}}</option>
        @endforeach
    </select>

How can I modify the code so that this doesn't happen?
Comment: What error? you need to add more info...
Comment: You are validating nothing, the method you are sharing it is literally just showing the view, did you mean `store` instead of `create`?
Comment: It's not the validation error I need to show. Maybe you didn't read well, I want to return the old value of my select without losing it in case a validation error appears. Now I hope I was clearer.
Comment: I need to see how you are validating... I have 6+ years of experience with Laravel, if I ask for something, please show that info... I am asking because if you are using a `FormRequest` (if you know what that is), then it should be working, if it is a manual validation, then I could try seeing the data...
Answer: How can you select back what failed if you did not even ask for the old value?
This may or not work depending on how you are validating, but you did not want to show that...

    Select*
    <select class="form-select" id="nationality" name="nationality" aria-label="Floating label select example">
        @foreach($nationalities as $nationality)
            <option value="{{$nationality}}" {{ old('nationality') === $nationality) ? 'selected="selected"' : '' }}>{{$nationality}}</option>
        @endforeach
    </select>

Comment: Updated answer; however it doesn't work like you told me
Comment: write another `` tag anywhere and put `{{ old('nationality') }}`, then send the form again, and when it refreshes, see if it has data, if it is printing something
Comment: tried but it doesn't work
Comment: I am getting very frustrated with you... what does `tried but it doesn't work` mean? I did ask, WHAT ARE YOU GETTING BACK? it is not "going to work or not".... god...
Comment: I get nothing, if I get any error I would write it
Comment: Try using `dd(old('nationality'))`...
Comment: I get `null` ...
Answer: <option value="{{$nationality}}" @selected(old('nationality')==$nationality)>
 {{$nationality}}
</option>

add the @selected directive in blade.
Comment: tried but it doesn't work
Comment: put this somewhere in view file. `{{print_r($errors->all())}}` then don't select any options so that validation fails and let redirect to the same page. Check if it is an empty array or has some elements in it.


Show progress of wallpaper android

Question: I am creating a wallpaper app and I'm trying to get the current state of it when it's loading and get this information and set it on a progress bar. I know how to get some information about the wallpaper but I don't know how to get the current status.
try {
  WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);
} catch (IOException e) {
  e.printStackTrace();
}

How can I get this event? I've tried many things but failed.
Answer: There's no need answers anymore. I found a solution. If someone needs it, here's what I did:
try {

                                    if (resource != null){

                                        WallpaperManager.getInstance(getApplicationContext()).setBitmap(resource);
                                        Toast.makeText(WallpaperDetailsActivity.this, "Aplicado", Toast.LENGTH_SHORT).show();

                                        progressBar.hideProgressBar();

                                    }

The resource I have add is the bitmap and I used glide to convert it. I hope It helps someone.

Show progress of wallpaper android


"Expression cannot contain lambda expressions" - Exception

Question: I tried to select and split a list from list of object like this :
GlobalV.LatestNews.Select(x => x.Source.Split('/').ToList().FindLast(y=> y!="")).ToList();

but I got an exception in FindLast(y=> y!="") said

expression cannot contain lambda expressions

I don't understand why !!!? I tried RemoveAll and ..etc but I got the same exception in each time.
Comment: Are you trying to run this in Visual Studio debugger's watch/quickwatch windows? if so it doesn't support lambda expressions.
Comment: No it is not the same question. Of course I checked and I debugged it and I don't have anything empty !!!
Comment: The exception is saying Expression. Normal Linq-to-objects doesn't use expressions, but lambda's which are compiled into the code. What enumerable type is your LatestNews? Is it an IQueryable, and is GlobalV a context? Is there EF or L2S involved here?
Comment: Could you answer @Nightwish91 's question? Are you trying to do it from one of the debug windows? Or is this happening when you try to compile your code?
Comment: "I got an exception" - post the **full details** of the exception you got.
Answer: Although it doesn't directly solve your problem, why don't you let the Split method handle the part you are trying to solve through the lambda expressions at the end?
var lastNonEmptySourceEntries = LatestNews.Select(x => x.Source.Split( new []{'/'}, StringSplitOptions.RemoveEmptyEntries).LastOrDefault());


Bash script exits unexpectedly

Question: I am writing a wrapper script around mail. There is a function in the program that I need for looping back to the main menu, but just before the function is declared, the program just exits back to the main prompt. Here is the code:
function restart ()
{
    m
}
clear
echo Working...
echo If you are prompted for your sudo password or asked if you want to continue, then you are being
echo prompted to install mailutils. This is normal upon first-time use, or
echo use on a computer without mailutils installed.
echo
echo Starting in 5 seconds...
sleep 5
echo Examining dependencies...
dpkg -l | grep -qw mailutils || sudo apt-get install mailutils
echo Starting client...
function m ()
{
    clear
    echo Welcome to the Terminal GMail Client, or TGC!
    echo Please enter your gmail address:
    read acc
    name=${acc%@*}
    echo Welcome, $name! Would you like to read[R] or write[W] emails?
    read opt
    if [ $opt=="R" ] || [ $opt=="r" ]
    then
        echo Working...
        sleep 1
        clear
        mail -u $acc -p
        restart
    elif [ $opt=="W" ] || [ $opt=="w" ]
    then
        clear
            echo Working...
        sleep 1
        clear
        echo Enter the subject here:
        read sub
        echo Enter the recipients address here:
        read rec
        echo Enter carbon copy [CC] here or leave blank for none:
        read cc
        echo Enter blind carbon copy [Bcc] here or leave blank for none:
        read bcc
        echo Enter the body of the email here:
        read body
        echo Sending to $rec...
        mail -s $sub -c $cc -b $bcc --user=$acc $rec "$body"
        echo Done! Going to main menu in 2 seconds...
        sleep 2
        restart
    fi
}

You see, there is no error, and I am put back at the prompt right after line 15, after 'Starting Client...'.
Comment: Declare function `m` before the function `restart` in order to let it know what `m` is.
Comment: Looking at your example again, it appears that you don't need `restart`.  But we warned about the trap of infinite recursion since you seem to be invoking `restart` from `m` and vice-versa.
Comment: Moreover, you should consider specifying any error message in your question.  Voting to close as _typo_.
Comment: But then wouldn't `m` not know what `restart` is?
Comment: When is `m` called the first time? I'm hoping you have a line after all of those you posted that invokes `m`. Otherwise, it will just exit after all declarations. And the last printed line would be "Starting client..."
Comment: This is poor design, you should not be apt-getting in the middle of a script for dependencies.   You should create a simple script that does the work and then create a DEB package for it which in-turn gets all the dependencies.
Comment: Yes, after the starting client line, all that the script does is define a function. Then, that definition the last command and so it exits. Your script doesn't call any of the functions it defines.
Comment: How is this a "gmail client", by the way? It doesn't appear to be related to Google mail in any way. It's a wrapper around the `mail` program. What is your plan for allowing the user to get replies to the mails they send?
Comment: What are the `sleep` calls for? They'll lose you some users very quickly.
Comment: The wording is a bit unlucky but I disagree with the question being off-topic, voting to reopen as the issues with this script can easily be addressed.
Answer: As others have pointed out in the comments: there's no need for multiple shell functions and recursion - a simple while loop will do.
The following is a revised version of your code with proper quoting and rudimentary error handling. Your script will need a lot more input validation and error checking to stand the test of real-world use.
But perhaps this will get you started.
#!/usr/bin/env bash

clear
echo 'Working...'
echo 'If you are prompted for your sudo password or asked if you want to continue, then you are being
prompted to install mailutils. This is normal upon first-time use, or
use on a computer without mailutils installed.'

echo 'Starting in 5 seconds...'
sleep 5
echo 'Examining dependencies...'
dpkg -l | grep -qw mailutils || sudo apt-get install mailutils || exit

clear
echo 'Starting client...'

while true; do
  echo 'Welcome to the Terminal GMail Client, or TGC!'
  echo 'Please enter your gmail address:'
  read -r acc
  name=${acc%@*}
  echo "Welcome, $name! Would you like to read[R] or write[W] emails or quit[Q]?"
  read -r opt
  case $opt in
    r|R)
      echo 'Working...'
      sleep 1
      clear
      mail -u "$acc" -p || { echo "ERROR: Please try again." >&2; continue; }
      ;;
    w|W)
      clear
      echo 'Working...'
      sleep 1
      clear
      echo 'Enter the subject here:'
      read -r sub
      echo "Enter the recipient's address here:"
      read -r rec
      echo 'Enter carbon copy [CC] here or leave blank for none:'
      read -r cc
      echo 'Enter blind carbon copy [Bcc] here or leave blank for none:'
      read bcc
      echo 'Enter the body of the email here:'
      read -r body
      echo "Sending to $rec..."
      mail -s "$sub" -c "$cc" -b "$bcc" --user="$acc" "$rec" "$body"  || { echo "ERROR: Please try again." >&2; continue; }
      echo 'Done! Going to main menu in 2 seconds...'
      sleep 2
      ;;
    q|Q)
      echo 'Goodbye.'
      exit 0
      ;;
    *)
      echo 'ERROR: Unknown command. Please try again.' >&2
      ;;
  esac
done

Bash script exits unexpectedly


What is this part on my new cooktop?

Question: I just got a Samsung NA36N7755TS cooktop secondhand. In between the rings of the power burner, there is a little metal part sticking up. It came significantly bent (damaged in transport). I bent it back mostly upright with a wrench, but I'm not sure what it actually is or is supposed to be doing. I can't find it in any of the drawings of the cooktop. Does anyone know what it is? Thanks!
Comment: Is there one of these on each burner? If it only on this one burner, then it might be a temperature sensor. It might be a burner that has automatic control to keep a saucepan at a constant temp, usually below boiling.
Comment: Looks like an igniter for a gas burner.
Comment: @JackAidley the whole cooktop got pretty beat up in transit (even the metal grating was damaged). I am having to replace several parts on it that were damaged. I was able to find images of the bent prong on a new cooktop and confirm that it is straight on that cooktop.
Comment: It's only on this burner.
Comment: The logic of bending things when dealing with gas escapes me - an entry for a Darwin Award maybe…
Comment: I mean this is clearly not a part of the gas system… I'm trying to figure out what this is so I can decide whether I need to replace it
Comment: @JonCuster the igniter is on the other side, as seen in bottom picture ... there is even a lightning bolt icon next to it
Comment: the metal part looks like it has a flat side ... it may be an adjustment control
Comment: @jsotola I think the flat bit is from where something smacked into it and bent it haha. I found that this is built onto the burner cup assembly… still not sure what it is though!
Comment: https://partsdr.com/part/dg62-00162a-burner-cup-orifice?gclid=CjwKCAjw2f-VBhAsEiwAO4lNeBFq4lwLx3YgcBv-uwDdc9y_ocqT9yfp8EyNQ2KNJmM_z7bACv0LZBoCbHUQAvD_BwE
Comment: What makes you think it was bent in transit, rather than designed to be bent? It seems rather unlikely that a recessed part like that would be damaged in transit.
Answer: Figured it out! This appears to be a thermocouple designed for flame out detection: https://www.sinopts.com/How-important-is-the-flameout-protection-device-id3688335.html
Update: I'm not actually sure this is a functional thermocouple. See below.
Comment: @JACK Assuming this cooktop is like mine, the other burners have only a single burner/cap/etc. instead of two. In which case, the thermocouples for the others may be underneath the cap instead of between the cap and ring.
Comment: Then there should be one on each burner.
Comment: @JACK I actually have a suspicion about this. Here is another stove which seems to use the exact same power burner, made by Defendi SRL: https://www.homedepot.com/p/ROBAM-30-in-Gas-Cooktop-in-Stainless-Steel-with-4-Burners-including-20-000-BTU-Burner-ROBAM-G413/320110077
Comment: If you look at the second-to-last pic, you see that everything about that power burner looks identical to mine, except for the thermocouple which looks different (brass base, pointed tip instead of silver prong). Then, if you look at the burner cup part for my Samsung range, you see that the prong in question is actually built into the burner cup and has no wire leads coming from it as you might expect: https://partsdr.com/part/dg62-00162a-burner-cup-orifice
Comment: Also, the Robam cooktop explicitly advertises flameout protection, while the Samsung does not. So, unless the thermocouple-based flameout mechanism is somehow sneakily self-contained inside the burner cup on my stove, my suspicion is that the prong on my stove is actually a non-functional piece of metal serving as a placeholder for a thermocouple protection feature which Samsung could have opted to include on this burner, but chose not to. As to why it would prong-shaped instead of flat, I wonder if it has something to do with the gas flow being designed assuming presence of a thermocouple?
Comment: a thermocouple is an electrical device ... if there are no wires, then it is not a thermocouple
Comment: @jsotola agreed, I think this prong was pushed into the hole where a thermocouple would go had Samsung decided to fit this burner with a thermocouple.

What is this part on my new cooktop?


Switching Workspace with 3 finger gesture on Ubuntu 16.04

Question: hey guys i am having trouble to setup the 3 finger gesture on my Ubuntu 16.04
I download touchegg and change the action type etc..:

<gesture type="DRAG" fingers="3" direction="LEFT">
    <action type="SEND_KEYS">Control+Alt+Left</action>
</gesture>

<gesture type="DRAG" fingers="3" direction="RIGHT">
    <action type="SEND_KEYS">Control+Alt+Right</action>
</gesture>

then on synclient TapButton3 = 1 and Clickbutton3 = 1 and put the same properties for 2 = 0.
3 finger gesture doesnt work at all. I dont want to use eastroke since then I would need to use a usb mouse.
I also checked if my touchpad on my laptop recognizes 3 fingers -> indeed it does.
What can I do guys, please help
Answer: Try,
synclient TapButton3=0 [instead of 1]
synclient ClickButton3=0 [instead of 1]
touchegg
Answer: Hey guys I have found a way to enable the 3 finger gesture. Follow the following link: https://wdullaer.com/blog/2015/10/08/multitouch-trackpad-gestures-with-touchegg/
When you reach Configuring Touchegg do the following:

Go to Keyboard setting and select shortcuts
on the left side choose Navigation
scroll all the way down and assign the following keyboard combination for "Switch to workspace left" and same for right:

.... left = Super+Left
.... right = Super+Right

The Super key = Windows key on the keyboard (for Windows & for Mac it is the Command key)
Next step is to follow the Configuring Touchegg and change the config file. The config file should look like this:
<application name="All">
    <gesture type="DRAG" fingers="3" direction="RIGHT">
            <action type="SEND_KEYS">Super+Left</action>
    </gesture>
    <gesture type="DRAG" fingers="3" direction="LEFT">
            <action type="SEND_KEYS">Super+Right</action>
    </gesture>
</application>


Laravel 5.4 - how to get and save database.sqlite located in the database folder

Question: I have a backup and restore database menu in my application, here I use sqlite for my database, I want to implement import and export database system like in phpmyadmin, and I am thinking of how to access database.sqlite in the database folder
I have tried it this way
Backup

and got the error
is there any way to get database.sqlite or maybe an easier way to backup and restore sqlite database on laravel 5.4?
Answer: Since this file is not in public directory, you need to create a symbolic link between the database and public/database directories to make this work:
ln -s /full/path/to/laravel/database /full/path/to/laravel/public/database

Or you can create a controller method and download this file with:
return response()->file(database_path('database.sqlite');

I also want to say that it's terribly insecure way yo backup the database and you should consider getting this file via SSH or something.
Comment: thanks, it works fine, but I do not get the name and extension of the file when trying to save it as in the picture

[image](https://i.imgur.com/ZIkxody.png)

which I expect like this

[image](https://i.imgur.com/VYkceke.png)
Comment: @IndraSukmajaya pass file name as the second parameter. There is a link in my answer, you can read more about this by clicking the link.


man  doesn't display anything after package installation with conda on Ubuntu 17.10

Question: When I try to get the manpages with man it seems to display nothing and behaves as though I just pressed enter
~$ man ls
~$ man man

I have tried solutions from these pages to no avail
question1 question2. This last question matches my condition exactly but the fixes doesn't seem to work. Although info seems to work.
Here are some additional information:
~$ man --version
man 126.96.36.199

~$ type -p man
/usr/bin/man

~$ type -t man
file

~$ manpath
/home/abhilash/anaconda3/man:/usr/local/man:/usr/local/share/man:/usr/share/man:/usr/lib/jvm/java-8-oracle/man

~$ uname -a
Linux abhilash-ThinkPad-T440 4.13.0-38-generic #43-Ubuntu SMP Wed Mar 14 15:20:44 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

UPDATE
~$ type -a man
man is /usr/bin/man

~$ env | grep 'PAGER\|^MAN'
~$

UPDATE 2
~$ ls -1 /usr/share/man/man1 | wc -l
2145

~$ ls -l "$(type -p pager)"
lrwxrwxrwx 1 abhilash abhilash 18 Apr 16 18:43 /home/abhilash/anaconda3/bin/pager -> ../lib/R/bin/pager

~$ ls -l "$(readlink "$(type -p pager)")"
ls: cannot access '../lib/R/bin/pager': No such file or directory

Comment: How about `ls -l "$(type -p pager)"` and (assuming it is a symlink): `ls -l "$(readlink "$(type -p pager)")"`
Comment: Show also: `type -a man` and `env | grep 'PAGER\|^MAN'`
Comment: I've added them as an update
Comment: Do you have any files in `/usr/share/man/man1/`?
Comment: @terdon : I have 2145 files in that folder.
Comment: @glennjackman The second command seems to say there is no such file. Is that expected ?
Answer: Turns out, after the anaconda installation or some package installation through conda, the default pager is re-written. The exact cause of this is unknown.
Just some more information
~$ anaconda --version
anaconda Command line client (version 1.6.9)
~$ conda --version
conda 4.4.10
~$ history | grep conda
  108  bash Anaconda3-5.1.0-Linux-x86_64.sh
  110  anaconda-navigator
  181  anaconda-navigator
  187  anaconda-navigator
  311  conda info --envs
  312  conda install rpy2
  313  conda search PySide
  314  conda search Python
  366  conda install findspark
  367  conda info --envs
  370  conda install findspark
  373  conda search findspark
  374  conda install -c conda-forge findspark
  495  anaconda --version
  496  conda --version
  497  conda list
  499  history | grep conda

My strongest guess is that rpy2 installation had this effect of changing the pager information given the time of events.
But these are the steps I took to solve the issue.
~$ update-alternatives --display pager
pager - auto mode
  link best version is /bin/less
  link currently points to /bin/less
  link pager is /usr/bin/pager
  slave pager.1.gz is /usr/share/man/man1/pager.1.gz
/bin/less - priority 77
  slave pager.1.gz: /usr/share/man/man1/less.1.gz
/bin/more - priority 50
  slave pager.1.gz: /usr/share/man/man1/more.1.gz

~$ rm /home/abhilash/anaconda3/bin/pager

Ensure that the pager defaults to the one that came with man-db by typing the following to confirm
~$ ls -l "$(type -p pager)"
lrwxrwxrwx 1 root root 23 Apr  9 13:57 /usr/bin/pager -> /etc/alternatives/pager

This solution was arrived at after going through this link in an attempt to set the pager to default.
Thanks to glenn and terdon for their inputs in solving this issue.
Comment: +1 for both your Q and A. Don't forget to click the check mark next to your answer in 40 hours or so when it let's you.
Comment: For this  this was caused by Microsoft R Open.... `which pager` showed that I wasn't using `/usr/bin/pager`. Just had to correct my $PATH order and it was fixed.
Comment: Just the `rm /home/abhilash/anaconda3/bin/pager` would have probably done it.
Comment: @WillZ is this more of an Anaconda problem or an R problem?
Comment: @AaronHall I can't remember exactly, as far as I can recall for me it happened after I installed MRO.
Comment: Wow, never could have guessed it without this comment. Thanks a lot, Abhilash.


Possible to use iPhone(iOS) as a webcam on Ubuntu?

Question: I have a work issued iPhone X I'd love to use as a webcam on my machine.  Has anyone had success doing this?  What software stack was used?
Comment: You must export or share or stream the camera using an iOS app. The phone is not a dumb external device - it's a fiendishly clever, powerful computer *pretending* under very limited circumstances to be an external device.
Answer: You can use Iriun to do this. You will need to download the app to your iPhone and install the linux client (a .deb file for Ubuntu 18.04 or higher).
If what's above doesn't work you can try to use Droidcam instead. Follow the instructions to set up the client in the previous link and then download the Droidcam app on your iphone from the App Store!
Comment: Same here. iPhone app says "Waiting for the connection" and Ubuntu app says "No phone available". Reinstalled both but still no connection.  Instead, I was able to get a different app -- [DroidCam](https://www.dev47apps.com/droidcam/linux/) -- working. :-)
Comment: I was off to a great start.  Sadly, even though both devices are on the same wifi network, the server is not finding the phone where I have the app installed and running.
Comment: You save my day.
Comment: @Eddiefiggie huh, seems like a bug to me. Maybe try reinstalling the iPhone app or  restarting both computers..
Comment: @sh37211 Thanks I updated my answer!


How to finish door frame as thin as possible

Question: I was dumb and didn't measure the laundry room entry way well enough and had to remove the molding to fit the units in.
In order to allow them to come out in the future I want to make the doorway as wide as possible. I tried doing thin drywall but it was too narrow of an entry way. I'm thinking just using drywall mud? And maybe some mesh wire? Any thoughts welcome!
Comment: Are you putting a door in?
Comment: I am not putting a door
Comment: How much space do you have between the jack studs, and how much space do you need to get the machines out?
Answer: I wouldn't put drywall mud on the wood. The proper solution probably is to reframe the opening wider, it looks like there is at least 3 inches on the right hand side depending on how wide your casing is.
If you want something quick and easy and are fine with less than perfect finish, you could leave the rough framing exposed, cut the drywall back a little from the wood frame edge and either refinish the drywall with a profile to finish the rough drywall edge or install a small piece of trim about 1/2"x1/2" to cover the drywall edge, and then install your casing to that edge. Then paint and finish, you can use some wood filler to fix the rough framing a bit although it will likely never look perfect.
Answer: A skim on framing lumber will never survive life.
A better strategy might be to attach a jamb with screws (and don't hide the screw heads — just countersink them perfectly flush). You could use trim head screws if you wanted them less obvious.
Comment: Drywall joint compound on framing lumber _can_ indeed last. My living room coat closet says that it'll last about 20 years. Sure, it probably wasn't the ideal way of doing it, but I was 20-something and the internet wasn't around to tell me what I couldn't do or what I should do...
Comment: @FreeMan — I'm both impressed and surprised. Can you share details? (Type of mud, mesh tape or not, type of corners…)
Comment: @Freeman I have a special recipe, check my answer ;)
Answer: How to make DIY ultrathin "drywall":
Ingredients:

Fiberglass fabric, the kind house flippers put on the walls to hide cracks. Sold in rolls. It's usually meant to be painted, but we won't be doing that. Get one without too much texture. This plays the part of the mesh wire you're suggesting, but it is much easier to smooth.

Your choice of drywall mud or spackle of the easy to sand kind.

Universal primer (product may depend on country, read instructions).

It turns out that drywall mud (at least the French ones) sticks extremely well to this particular universal primer. The primer is intended for thinset and self leveling compounds.
Pure plaster will not stick to this primer, but plaster-based compounds (like mud, spackle, etc) contain extra ingredients that make them stick to painted walls, which also work very well on primers. YMMV, but this essentially allows to coat anything the primer will stick to with plaster-based mud/spackle products that can then be sanded to a smooth finish.
Clean up the surface, maybe sand, depending on circumstances.
Apply one coat of mud.
Lay the fiberglass over the mud and smooth it with a spatula. As the mud is trapped between the fiberglass and the substrate, this hides all imperfections and creates a smooth finish. It works a lot better than the glue that is usually sold with these fiberglass rolls...
Apply another coat of mud. This makes a tough fiber-reinforced coat that won't flake off.
Wait for it to dry, then sand.


Angularjs route html5Mode direct url in .net MVC

Question: I've seen a couple of similar questions/answers, but I still seem to be missing something. Everything works fine until I refresh the page or go to a URL directly.
I can either get a 404 or create the same url in mvc, but then it serves up the partial only on refresh and doesn't include the layout page.
There were a couple that suggested changing the MVC routing to:
routes.MapRoute(
    name: "Application",
    url: "{*url}",
    defaults: new { controller = "Home", action = "Index" }
);

When that is implemented, it means I can't access any other URL on the site normally and unless I am missing something, basically everything has to be put into a rest api or write a custom route for every url. Neither sounds very good.
So how can I have an html5 url (no hash tags in valid browsers) with angularjs and be able to browse to eg. Home/About or Home then click a link to About and have them show up the same with the same base layout page?
Comment: i think this is what you're looking for http://stackoverflow.com/questions/25730797/asp-net-mvc-hosting-angular-app-with-html5mode-and-routing
Comment: That looks like it's saying the same thing. Re-route all requests. Not wanting to use API calls for everything seems more challenging than I would have figured. Was thinking of writing a filter in MVC to re-route all non ajax requests, but maybe there is a better way.
Answer: This may not be the best answer, so if anyone has any better ideas, please comment, otherwise maybe this will help someone else.
I realized that the MVC Ajax directive didn't detect angular calls, so I couldn't automate that side.
So in angular I did something like
.when('/Home/Contact', {
    templateUrl: '/Home/NgContact'

In my MVC controller I have 2 actionresults:
public ActionResult NgContact(){
    ViewBag.IsFromNg = 1;
    return Contact();
 }
 public ActionResult Contact() {
    return View("Contact"); //have to type in name, may look for NgContact.cshtml
 }

Finally on any views these may call I put:
@if (ViewBag.IsFromNg == 1){ Layout = null; }

So there is a little repetition with each Actionresult having 2 copies, 1 for a full page load and 1 for any calls angular makes, but only 3 extra lines each.


How to convert a MS Office DOC/XLS/PPT & PDF to image on Android

Question: We need to be able to import Office documents as images into an app. On Windows we use LibreOffice which has a command line --convert flag.
Now we need to do the same for Android and iOS.
LibreOffice is not ready for Android yet.
Open Office for Android (AdrOpen Office) is there, but it does not have the --convert line option
One possibility I am looking at is to use JodConverter, but the solution needs to work offline - my reading of JodConverter is that it "uses openeoffice.org", and I'm not if this means it accesses the web site when doing the conversion, or it simply requires some software components from openoffice.org to be installed locally.
Note I am not asking how to open the documents, but how to convert them to an image, which we then import as a background in our app. We do not need to "live edit" them.
Answer: you can use PDF2JPG app to convert PDF to jpg. This app is available on google playstore freely. for doc to jpg conversion , you need to use the combination of two apps. First you need to use Doc To Pdf app from playstore for convert it to PDF, which is freely available on google playstore then convert PDF to jpg.


How to find a previous value to a given x in trees in Haskell?

Question: The task is to find a previous value to the given x in a tree in Haskell. IMPORTANT! Using Lists in any part is not allowed:
data SearchTree a = Leaf a | Node a (SearchTree a) (SearchTree a)

t1 = Node 5 ( Node 4 ( Leaf 1)
                     ( Node 5 (Leaf 4) (Leaf 5))
            )
            ( Node 7 ( Node 6  ( Leaf 5 ) ( Leaf 7  ))
                     ( Node 10 ( Leaf 9 ) ( Leaf 11 ))
            )

previousVal :: Ord a => a -> (SearchTree a) -> a
previousVal x t = previousValHelp x t

previousValHelp x (Leaf n) = error "Es gibt nichts kleineres"
previousValHelp x (Node n l r) = (max n (max (previousValHelp x l) (previousValHelp x r))) < x

For example previousVal 9 t1 should give 7 out.
I managed to make this code, but it's wrong... Does anyone here have an idea?
Thank you!
Comment: There are many questions on binary search trees recently. Is this part of a lecture? By the way, `previousVal :: Ord a => a -> SearchTree a -> Maybe a` would be a little bit more safe.
Comment: I'm afraid I don't quite understand your question. Could you explain why it should return `7` given `9` and `t1` and input? Also, I don't really see a point in making the `previousValHelp` function. `previousVal` just directly calls it, without doing anything else. Why not just define `previousVal` the way you have `previousValHelp`?
Comment: What do you think `previousVal 5 t1` should be? What about `previousVal 8 t1`?
Comment: I suggest you read about [zippers](http://learnyouahaskell.com/zippers) and then generalize this to look for an element `n` before or after the given one.
Answer: Haskell is about types. So it's best to start with the type signature of a function instead of the definition. And it also makes sense to let the type checker tell you what's wrong. It often leads to the solution.
So, I tried to compile your code. Compiler output can sometimes be a bit confusing, but that's something everyone has to go through. I cheated a little to make the output more useful by changing previousVal x t = previousValHelp x t to previousVal = previousValHelp (that is called eta reduction, but you may just ignore it if it's confusing for you).
Here is the output:
SearchTree.hs:11:15:
    Could not deduce (a ~ Bool)
    from the context (Ord a)
      bound by the type signature for
                 previousVal :: Ord a => a -> SearchTree a -> a
      at SearchTree.hs:10:16-48
      'a' is a rigid type variable bound by
          the type signature for
            previousVal :: Ord a => a -> SearchTree a -> a
          at SearchTree.hs:10:16
    Expected type: a -> SearchTree a -> a
      Actual type: Bool -> SearchTree Bool -> Bool
    Relevant bindings include
      previousVal :: a -> SearchTree a -> a (bound at SearchTree.hs:11:1)
    In the expression: previousValHelp
    In an equation for 'previousVal': previousVal = previousValHelp

See how it tells you what type it expected of previousValHelp, but what it got instead:
Expected type: a -> SearchTree a -> a
  Actual type: Bool -> SearchTree Bool -> Bool

This type error shows also the logical error. The definition of previousValHelp is basically a foo < bar (just ignore the brackets and the recursion for a second). Mind that the above two lines do not show up in your initial version of the code... so try to figure out the meaning of the very first few lines of the whole compiler output as well.
Anyway, let's check now what type (<) has in ghci (< is the infix version of (<)):
Prelude> :t (<)
(<) :: Ord a => a -> a -> Bool

So it returns a value of type Bool (if given those two a arguments). Makes sense.
Remember how I told you to ignore the recursion and brackets for a second. Now let's figure out why not just the "return type" of your function is Bool, but the rest as well. Let's have a look:
previousValHelp x (Node n l r) =
  max n (max (previousValHelp x l) (previousValHelp x r)) < x

This might get a bit tricky. Since we already know that previousValHelp is a function that returns a Bool if given two parameters, we can deduce that the recursive calls (previousValHelp x l) and (previousValHelp x r) also return a Bool. That means we are running the inner function max (previousValHelp x l) (previousValHelp x r) with two Bool parameters and get back a Bool. See the type signature:
max :: Ord a => a -> a -> a

Now we have the outer function max n (max (...) (...)) as well... we already know the type of it's second parameter which is Bool (see above). Since the types must be consistent (max True True works, but not max True 1) the first parameter n is assumed to be Bool as well. Aha. Check your definition of SearchTree... n is the type parameter of our SearchTree and as such we get SearchTree Bool!
Similarly, the parameters for (<) must be consistent as well. True < False works, while True < 1 does not.
So the last step is to figure out the type of x. We already know that the left-side parameter of < is Bool... so x must also be Bool which is our first function parameter.
My guess is that you probably want to use (<) in a way that lets you choose what you want to do... instead of just returning the result.
For that purpose, there are guards.
Again: for a language like haskell which has such a strong focus on types... it's really crucial to learn how to read type/compiler errors.
Answer: Note: in the below I assume that "previous value to x" means "the greatest value in the tree less than x" and that a SearchTree is a Binary Search Tree (ie. sorted).
Let's first have a look at why your code isn't working how you want it to.
One of the great things that Haskell gives us is expressive types, along with type inference, so let's see what type it thinks your previousValHelp function has:
Prelude> :t previousValHelp
previousValHelp :: Bool -> SearchTree Bool -> Bool

Ah! There's a problem! Our implementation of previousValHelp only works for SearchTree Bool! That's not right, though, we want it to work for all a which fit the constraint Ord a. Try to work out why this is. (I'm not going to explain it here, but try working through the types to see why the SearchTree must be a SearchTree Bool.)
Let's start re-writing our previousVal function. We'll start with a type signature:
previousVal :: Ord a => a -> (SearchTree a) -> Maybe a

This says "assuming we can compare objects of some type a, we're going to define a function which takes an a, and a SearchTree containing as, and returns to us either an a (wrapped in Just), or Nothing". (We're going to use a Maybe a instead of error, because then we can use the type system to make sure our program doesn't crash by forcing us to explicitly handle the Nothing result. It also makes the implementation of the recursive function much easier.)
Now, we know a SearchTree has two possible "shapes": either a Node or a Leaf. We'll have to implement a case for both of them.
previousVal x (Node v l r) = _
previousVal x (Leaf v) = _

Let's start with the Node case. There are two possible cases here: if the value at this Node is less than the value we're looking for, then we want to go down the right subtree (r), otherwise we want to go down the left subtree (l).
previousVal x (Node v l r) | v < x = previousVal x r
                           | otherwise = previousVal x l

For Leafs the logic is even easier: if the value at the Leaf is less than the value we're looking for then we can return the value (because there's nothing else below us that could be "closer" to it than where we are currently). Otherwise, we just return Nothing.
previousVal x (Leaf v) | v < x = Just v
                       | otherwise = Nothing

Now, if you run the code we've written up until this point, you should find some cases where it works, and some where it fails. For example:
Prelude> previousVal 5 t1
Just 4
Prelude> previousVal 9 t1
Nothing

Why does it seem to work some times, but not others? Well, it turns out we've actually got a bug in our Node case above. See, when we go down the right-hand branch there the possibility that there won't be any values in that subtree which are less than x. In that case, the right hand tree will return a Nothing back to us. But if the right hand subtree returns a Nothing, then the Node we're currently at contains the largest value smaller than x, so we should return Just v instead. Instead of the Node case above we should have something like this:
previousVal x (Node v l r) | v < x = case previousVal x r of
                                       Nothing -> Just v
                                       value -> value
                           | otherwise = previousVal x l

Now it should work for 9, too:
Prelude> previousVal 9 t1
Just 7