w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Ruby String variable returning true for .is_a?(Array)
def do_stuff(x) x = x.lines.to_a if x.is_a? String x end data = [ "hello world", [1, 2, 3] ] data.each do |item| p do_stuff item end Now, with unless: def do_stuff(x) unless x.is_a?(Array) x = x.lines.to_a end x end data = [ "hello world", [1, 2, 3], ['a', 'b'] ] data.each do |item| p do_stuff item end --output:-- ["hello ", "world"] [1, 2, 3] ["a", "b"] But it makes more sense to check for a String object before calling a String method on the object than checking for not an Array.

Categories : Ruby

if statement returning true
Because this is wrong if( $imagetype == "image/jpeg" || "image/gif" ) { /*...*/ } Should be if( $imagetype == "image/jpeg" || $imagetype == "image/gif" ) { /*...*/ } Or even if( in_array($imagetype, ["image/jpeg", "image/gif"]) ) { /*...*/ } That is, because non-empty string is considered true, so the IF condition was met.

Categories : PHP

Why is my boolean of value 0 returning true?
This blog by Jeffrey Snover offers some insight on the behavior of booleans in Powershell. Below is an excerpt, where he creates a simple function "test" to return true or false depending on the input parameter: PS> test "0" TRUE PS> test 0 FALSE PS> test 1 TRUE PS> test 0.0 FALSE PS> test 0x0 FALSE PS> test 0mb FALSE PS> test 0kb FALSE PS> test 0D FALSE PS> test 0.00000001 TRUE “0” is TRUE because it is a STRING and it has a length of 1. 0 is FALSE because it is a number and that number is 0. In PowerShell, any number which evaluates to 0 is FALSE and every non-zero number is TRUE. The example shows you a floating point zero, a hexadecimal zero, 0 megs, 0 kilos, 0 decimal, there are all sorts of zeros but to PowerShell, they all evaluate

Categories : Dotnet

string.contains is always returning true
You used assignment operator in the if statement instead of equality. It should be like this: if(check == true){ teststring[i] = storestrings[i]; //System.out.print(storestrings[i]); } or simply if (check) { teststring[i] = storestrings[i]; //System.out.print(storestrings[i]); } In your code, when it reached check = true in the if statement, it assigns true to the check variable and returns true so the if condition always evaluates to true.

Categories : String

Any difference between returning False or True first?
The difference is that both the loops are checking for different results. The 1st loop is checking whether the $regexp matches all the elements of the array - In this case, it returns false as soon as a match fails and if the return statement after the for loop is reached, that means all the elements match. To be honest, not having the braces around the for loop can often be confusing (like it confused me first). I would suggest to add relevant brace: for ($i=0; $i<2; $i++) { if (preg_match($regexp, $names[$i])) { return true; } } return false; The 2nd loop is checking whether the $regexp matches any element of the array - In this case, it return true as soon as a match succeeds, and if the return statement after the for loop is reached, that means none of the eleme

Categories : PHP

Why is this Linq function returning true when it is not?
because you have instantiated list in the constructor causing it not to become NULL. maybe you mean, list.Where(o => o.Badge == badge).Count() != 0

Categories : C#

javascript code this is not returning true
The code within onreadystatechange is called an "event handler", and will execute only once your POST operation has finished. This is what your validatenewcat function is actually doing when you run it: var category = document.getElementById("cat").value; var url = "catnamecheck.do?id=" + category; xmlhttp.open("post", url, true); xmlhttp.send(null); xmlhttp.onreadystatechange = (code to be called later) return false; // <-- Always return false You need to move the code that requires the TRUE / FALSE result inside the onreadystatechange function, so that it is executed after the HTTP operation has finished: xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4) { if (xmlhttp.status == 200) { var temp = xmlhttp.responseText; obj =

Categories : Javascript

jquery validate always returning true
Did you add required to the HTML tag of the <input> or <textarea> ? IE: <input id="cemail" type="email" name="email" required/>

Categories : Jquery

Html.CheckBox returning value not true/false
This seems ridicouous but can you only return true/false from an MVC checkbox? I don't find it ridiculous. When you give it a second thought modeling a checked/unchecked state with a boolean variable actually makes sense. WHY! Because that's how the designers of the framework decided to implement the CheckBox helper. any ideas on how to get around this stupidity? By using a view model of course: public class MyViewModel { public int Id { get; set; } public bool IsChecked { get; set; } } and then assuming you had a collection of those you would use a checkbox and a hidden field to store the corresponding id of the item: @Html.HiddenFor(x => x.SomeCollection[i].Id) @Html.CheckBoxFor(x => x.SomeCollection[i].IsChecked) When the form is submitted you will

Categories : C#

PHP OOP checking if a class is returning true or false?
I don't think PHP cares about your return statement in your constructor. It should always return the object that was created (the instance of Ping). Since the instance of Ping is not null, if(new Ping()) evaluates to true and '1' is echoed. If pinging is really just one call, why use an object? You can have this statically defined in a static library of some sort (e.g. NetUtils). If pinging is more complex and you think that it fits the object oriented model, then perform the ping in two steps. Ping pingObj = new Ping(); pingObj->ping();

Categories : PHP

in_array returning false when it should return true
I think you want to check if $words is in $list: if(in_array($words[0], $list)) { ... } or define $stopwords: $stopwords = $list;

Categories : PHP

comparing 2 objects and returning true if they ok using operator
Assuming you really want the -= operator, a lead would be : const DateC & DateC::operator -= ( const DateC& rhs) { this->day = ?; // do something with rhs.day this->month = ?; // do something with rhs.month this->year = ?; // do something with rhs.year return *this; } But according to the title of your question, you are looking for == operator : Another lead : bool DateC::operator == ( const DateC &rhs ) const { if ((this->day != rhs.day) || (this->month != rhs.month) || (this->year != rhs.year)) { return false; } return true; } Use it as follows : bool ok = (DateC(1,2,2001) == DateC(11,2,2001)); // Returns false Note : Of course, you can replace my == by -=, but this would be

Categories : C++

in_array comparing two different types and yet returning true
That is the expected output, you need to add a third value as TRUE to make it also compare the types, as can be seen in the PHP manual for in_array(): bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) The third value is default to FALSE, but you can change that with a simple: if (in_array($_SESSION['enemies'][$i], $clones[$j]->defendAgainst, TRUE)) EDIT: I think I know how you can find the problem yourself. I just found this question. Try changing the in_array() to the form of the foreach() of the first answer, but change the return TRUE; like this to see what it brings: foreach ($clones[$j]->defendAgainst as &$member) { if ($member == $_SESSION['enemies'][$i]) { var_dump($_SESSION['enemies'][$i]); var_dump($member); } }

Categories : PHP

Javascript RegEx.Test always returning true
if(result==true) { alert(date.value); } instead having single "=" have "==" , else you can use like this if (result) { alert(date.value); } and always remember this "1" == 1 // true "1" === 1 // false An example of type coercion at work. Basically anytime your value is the "same" but the type isn't then == works. Please use === everywhere. There's no need to use ==. checking for types is always better. If something breaks then you can convert from type a to type b

Categories : Javascript

IsNumeric function returning true for an empty cell
I have checked it with an empty cell right now (without involving a PDF file at all) and you are right: IsNumeric returns True for empty cells. I haven't ever had this problem because, when coding, I intend to not bring the in-built functions "to its limits" (determining whether an empty cell can be considered as numeric or not might be even discussion-worthy). What I do always before performing any kind of analysis on a cell (or a string in general) is making sure that it is not empty: Dim valIsNumeric As Boolean If (Not IsEmpty(Range("A1"))) Then valIsNumeric = IsNumeric(Range("A1")) End If Or in a more generic version (highly reliable with any kind of string under any circumstance): If (Len(Trim(Range("A1").Value))) Then valIsNumeric = IsNumeric(Range("A1")) End If Making

Categories : Excel

Ruby Set include function returning true even when item is not in set
From what you're saying, it seems like you're questioning why: ["#{foo}"].include?(foo) is always true where foo is the expression MD5.hexdigest(tweet[0]). But the above expression will always be true as long as foo returns a string, which MD5.hexdigest does.

Categories : Ruby

FileUpload isFormField() returning true when submitting file
Maybe it's a typo but you are missing a "name" attribute, wich is mandatory. <input id="attach-btn" type="file" name="someFile" style="display:none"/> After some testing, without a name in the field, the file input is not included in the List<FileItem>. You recieve just the submit input with a default value (in my case something like "send request"). Try it and tell us if it worked.

Categories : Java

Regular Expression issue in C# returning match true
The problem is that all parts of your regex are optional, that means that even an empty string will match your regex. Even if some invalid string were passed in, it would still match a zero-length substring at the start of the input. Also, you've escaped the slashes. This is not necessary in a verbatim string literal (a string literal starting with @). The string regular string literal "foo\bar" is equivalent to to the verbatim literal @"fooar" . I think you'll want to add start (^) and end ($) anchors to your pattern: new Regex(@"^(([a-zA-Z][0-9a-zA-Z+-.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$.-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$.-_!~*'()%]+)?$"); This will make ^ fail, but an empty string still matches (since all parts are still optional) and $ is still valid input. It's hard to tell e

Categories : C#

response.authResponse not returning true after facebook login
try this, don't test it with r.status === 'connected' if (r.authResponse) { //user is already logged in and connected FB.api('/me', function (info) { login(response, info); }); } else { //user is not connected to your app or logged out FB.login(function (response) { if (response.authResponse) { FB.api('/me', function (info) {}); } else { //user cancelled login or did not grant authorization } }, {scope : 'email'}); }

Categories : PHP

connectivitymanager.getActiveNetworkInfo() returning true when Internet is off (Android)?
You should call isConnected instead of isConnectedOrConnecting if you want to determine whether the device is connected at the time of call to isOnline. Generally, there are many problems/bugs with hardware-features APIs on the emulator, this might be one of them. Your code is fine.

Categories : Android

File.Exists returning true, not in Directory or VirtualStore
There are two possibilities that exist when referencing c:windowssystem32. One that you've noted, it could be redirected to %userprofile%AppDataLocalVirtualStore. The other: if you're running as a 32bit process on a 64bit system, you will automatically be redirected to c:windowssyswow64. Check to see if log.txt exists in c:windowssyswow64. If you want to reference certain locations on the system like c:windowssystem32 or c:program files, you must change the build configuration to x64 or "AnyCPU".

Categories : C#

regex returning true even if comma is not enclosed in double quotes
Because you are creating a character range here : /^\"[a-zA-Z0-9!#$%&\'*+-/=?^_`{|}~;,:<>()@[]]*\"$/ ^^^^^ This means all characters from + to /, this includes also the ,. INside a character class, you don't need to escape the normal regex special characters, but there is another one, that get a special meaning the -. So the correct character class would be /^\"[a-zA-Z0-9!#$%&\'*+-/=?^_`{|}~;,:<>()@[]]*\"$/ The alternative would be to put the - at the start or the end of the character class, in that cases it would not create a range and does not need escaping.

Categories : Javascript

Android Content Provider Query returning true when it should be false
In your query method, you are not putting the selection in the query you make. Hence, SURVEYNAME + " =?" is ignored. You need to call something like : return builder.query(db, projection, selection, selectionArgs, null, null, sortOrder); to pass your arguments to your database.

Categories : Android

strstr to find a word in a string using c returning true all the time
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1. Returning NULL (0) essentially means that the string was NOT found. Thus if(strstr(sentence,word) == 0){ printf("word found!"); } Should be if(strstr(sentence,word) != NULL){ printf("word found!"); } Source - http://en.cppreference.com/w/c/string/byte/strstr Additionally as Armin points out, you shouldn't use the address operator, &, in your printf. %s expects to have a pointer passed to printf and using the name of the array as sentence is actually the same as a pointer to the start of the array, i.e sentence == &sentence[0]

Categories : C

why is self.navigationController.visibleViewController returning true on view controller that is not visible
visibleViewController will always return an object (at least with your setup) which makes your if statement always true -- it doesn't return true only if the controller you have that code in is on screen. Instead you should use self.view.window as the test. It will only return true if self's view is on screen. You could also still use self.navigationController.visibleViewController, but compare it to self to see if they're the same.

Categories : Iphone

Beautifulsoup and Soupstrainer for getting links dont work with hasattr, returning always true
hasattr() is the wrong test; it tests if there is a a.href attribute, and BeautifulSoup dynamically turns attributes into searches for children. HTML tag attributes are not translated into Python attributes. Use dictionary-style testing instead; you loop over all elements which can include the DocType instance, so I use getattr() to not break on objects that don't have attributes: if 'href' in getattr(link, 'attrs', {}): You can also instruct SoupStrainer to only match a tags with a href attribute by using href=True as a keyword argument filter (not None just means True in any case): for link in BeautifulSoup(test.text, parse_only=SoupStrainer('a', href=True)): This still includes the HTML declaration of course; search for just a links: soup = BeautifulSoup(test.text, parse_only=So

Categories : Python

LinkedList Iterator next() throwing NoSuchElementException even when called after hasNext() returning true
I see these possibilities: lines is used from another thread lines.next() is called in // some more code... lines is bound to another instance in // some more code...

Categories : Java

Declaring a private, thread specific, variable in a kernel and then returning that variable to the host
Yes it is possible. Declaring a local variable in a kernel is private to each thread that you launch. So simply declare a variable, use it, and when you want to store result in the host , copy it to global memory. You could give a location to global memory passing a pointer to it as argument to the kernel. Example: __global__ void kernel(float *var) { float localVar;//local to each thread in execution ... //Computation which uses localVar ... *var = localVar; } After you use cudaMemcpy() to get it in the host. This example also is valid if you declare a local array. In that case you just have to copy an array instead of a single variable. Edit#1: Example of passing an array as argument to a kernel: __global__ void kernel(float *arrayPtr, int length) { .... } arrayPtr is a de

Categories : Multithreading

In var foo = true; the variable type for "foo" is what?
A yes or no / true or false / 1 or 0 is a boolean type variable, although Javascript doesn't really distinguish like most other languages do.

Categories : Javascript

If variable is true within foreach loop
Use a separate variable which you set to false before the loop. Inside the loop, set it to true if you got that certain status. Edit: Or, since you seem to have more than two possible status values you need to consider, set it to "approved" initially, and use a comparison function that tells you which of two status values is lower. Then, in the loop, use that function to set the global status to the minimum of itself and the current loop iteration's status.

Categories : PHP

Only submit AJAX form if the variable is true
Try to prevent default behaviour of your form's submit handler: $(function () { $('#submit').submit(function (e) { var isValid = document.getElementById("form-setting").checkValidity(); alert(isValid); //<<< ALERT HERE var data = {}; data.id = $("#id").val(); data.title = $("#title").val(); data.content = $("#content").val(); data.author = $("#author").val(); data.email = $("#email").val(); if (isValid) { alert('PASS'); //<<< ALERT HERE $.ajax({ context: this, //use for success callback type: 'POST', data: JSON.stringify(data), contentType: 'application/json', url: '/admin/setting',

Categories : Jquery

Python: How to make a variable true 40% of the time
import random num = random.randint(0, 4) context['showItem'] = True if num <= 1 else False Here I think @Xaranke's answer is better and more flexible. I also test the performance of random and randint on my laptop, the former is 10x faster.

Categories : Python

Django Admin Display row if a variable is true
Just override ModelAdmin.queryset() (or ModelAdmin.get_queryset() for 1.6+) class MyAdmin(admin.ModelAdmin): def queryset(self): qs = super(MyAdmin, self).queryset() if True: # however you get your condition return qs.filter() # whatever rows need to be included return qs.filter()

Categories : Django

Why does a variable with no value return true with empty? when used in a view)?
If it works, it means that your variable page_title is not nil. Test it in debug mode and report your findings :) hint: with pry you can put binding.pry just after base_title = "my app".

Categories : Ruby On Rails

Apply style on mouseover and when class variable is true
You should use MultiDataTrigger (msdn). Example: <Canvas> <Path> <Path.Data> <PathGeometry Figures="M 10,100 C 10,300 300,-200 300,100" /> </Path.Data> <Path.Style> <Style> <Setter Property="Path.Stroke" Value="Black" /> <Setter Property="Path.Fill" Value="LightGray" /> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Canvas}}" Value="True" />

Categories : Wpf

Memory Card not present still memory check returning true
Check for public static boolean isExternalStorageRemovable () Added in API level 9 Returns whether the primary "external" storage device is removable. If true is returned, this device is for example an SD card that the user can remove. If false is returned, the storage is built into the device and can not be physically removed. Environment.getExternalStorageDirectory() refers to whatever the device manufacturer considered to be "external storage". On some devices, this is removable media, like an SD card. On some devices, this is a portion of on-device flash More on this already answered by @CommonsWare here http://stackoverflow.com/a/5695129/786337 http://stackoverflow.com/a/15612964/786337

Categories : Android

PHP - Does 1 vs true, 0 vs false or verbosity of variable names affect performance?
I doubt that 1 vs true and 0 vs false has any appreciable performance impact, but if you want to know for sure you should create a benchmark. Variable name length should not make any difference. The compiler turns them all into internal pointers when it parses the script. Shorthand notations also shouldn't make much difference, the compiler should generate similar code for both. Your concerns all seem to be based on the assumption that the code is being interpreted line by line. PHP is compiled, not interpreted.

Categories : PHP

PROLOG - clause returns true for constants, but won't find solution for variable?
To prove sibling(clara, X), you first need to prove clara = x. But that doesn't work because it reduces to + clara = X, were + is the infamous negation as failure: Prolog tries to prove clara = X, which succeeds, and concludes that clara = X must therefore be false. You should either reorder your program to do the = check last instead of first, or use dif(clara, X).

Categories : Prolog

How to SELECT ALL FROM SQLite table and then save true or false answer into a variable?
Lookin at this line: var sql2 = 'SELECT * FROM Contacts', WHERE firstName = "'+firstname+'"; JS variable "firstname" is mistyped (No capital N on Name). This will turn your query into: 'SELECT * FROM Contacts WHERE firstName = "undefined"' Also, why is there ', before WHERE? I am surprised you did not get an error. Try rewriting your query like so: var sql2 = 'SELECT * FROM Contacts WHERE firstName = "'+firstName+'"';

Categories : Javascript

Returning a variable value outside if-else block
You need to declare meridiem outside the if block. You also need to use = to assign to meridiem after it's declared: string meridiem; /* ^^^^^^^^^^^^^^^^ */ if (midHour <= 12) { midHour12 = midHour; meridiem = "AM"; /* ^^^^^^^^^^^^^^^^ */ } else { midHour12 -= 12; meridiem = "PM"; /* ^^^^^^^^^^^^^^^^ */ } Otherwise the variable will go out of scope by the ending bracket.

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.