# Search Results

• ### Unary NOT/Integersize of the architecture

##### - by sid_com
From "Mastering Perl/Chapter 16/Bit Operators/Unary NOT,~": The unary NOT operator (sometimes called the complement operator), ~, returns the bitwise negation, or 1's complement, of the value, based on integer size of the architecture Why does the following script output two different values? #!/usr/local/bin/perl use warnings; use 5.012; use Config; my \$int_size = \$Config{intsize} * 8; my \$value = 0b1111_1111; my \$complement = ~ \$value; say length sprintf "%\${int_size}b", \$value; say length sprintf "%\${int_size}b", \$complement; Output: 32 64

• ### Numeric comparison difficulty in R

##### - by Matt Parker
I'm trying to compare two numbers in R as a part of a if-statement condition: (a-b) >= 0.5 In this particular instance, a = 0.58 and b = 0.08... and yet (a-b) >= 0.5 is false. I'm aware of the dangers of using == for exact number comparisons, and this seems related: (a - b) == 0.5) is false, while all.equal((a - b), 0.5) is true. The only solution I can think of is to have two conditions: (a-b) > 0.5 | all.equal((a-b), 0.5). This works, but is that really the only solution? Should I just swear off of the = family of comparison operators forever?

• ### Arithmetic operator confusion

##### - by Dusk
Why I'm getting two different values while using the arithmetic operators for the same value of variables. I've just altered little bit my second program, which is resulted in giving me the different output. Could anyone please tell me why? int number=113; int rot=0; rot=number%10; rot*=100+number/10; System.out.println(rot);//333 int number=113; int rot=0; rot=number%10; rot=rot*100+number/10; System.out.println(rot);//311

• ### What are these values representative of in C bitwise operations?

##### - by ajax81
Hi All, I'm trying to reverse the order of bits in C (homework question, subject: bitwise operators). I found this solution, but I'm a little confused by the hex values (?) used -- 0x01 and 0x80. unsigned char reverse(unsigned char c) { int shift; unsigned char result = 0; for (shift = 0; shift < CHAR_BITS; shift++) { if (c & (0x01 << shift)) result |= (0x80 >> shift); } return result; } The book I'm working out of hasn't discussed these kinds of values, so I'm not really sure what to make of them. Can somebody shed some light on this solution? Thank you!

• ### How do I indicate that a class doesn't support certain operators?

##### - by romeovs
I'm writing a class that represents an ordinal scale, but has no logical zero-point (eg time). This scale should permit addition and substraction (operator+, operator+=, ...) but not multiplication. Yet, I always felt it to be a good practice that when one overloads one operator of a certain group (in this case the math operators), one should also overload all the others that belong to that group. In this case that would mean I should need to overload the multiplication and division operators also, because if a user can use A+B he would probable expect to be able the other operators. Is there a method that I can use to throw an error for this at compiler time? The easiest method would be just no to overload the operators operator*, ... yet it would seem appropriate to add a bit more explaination than operator* is not know for class "time". Or is this something that I really should not care about (RTFM user)?

• ### C++ template class error with operator ==

##### - by Tommy
Error: error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const entry' (or there is no acceptable conversion) The function: template <class T, int maxSize> int indexList<T, maxSize>::search(const T& target) const { for (int i = 0; i < maxSize; i++) if (elements[i] == target) //ERROR??? return i; // target found at position i // target not found return -1; } indexList.h indexList.cpp Is this suppose to be an overloaded operator? Being a template class I am not sure I understand the error? Solution- The overload function in the class now declared const: //Operators bool entry::operator == (const entry& dE) const <-- { return (name ==dE.name); }

• ### How to pass multiple different records (not class due to delphi limitations) to a function?

##### - by mingo
Hi to all. I have a number of records I cannot convert to classes due to Delphi limitation (all of them uses class operators to implement comparisons). But I have to pass to store them in a class not knowing which record type I'm using. Something like this: type R1 = record begin x :Mytype; class operator Equal(a,b:R1) end; type R2 = record begin y :Mytype; class operator Equal(a,b:R2) end; type Rn = record begin z :Mytype; class operator Equal(a,b:Rn) end; type TC = class begin x : TObject; y : Mytype; function payload (n:TObject) end; function TC.payload(n:TObject) begin x := n; end; program: c : TC; x : R1; y : R2; ... c := TC.Create(): n:=TOBject(x); c.payload(n); Now, Delphi do not accept typecast from record to TObject, and I cannot make them classes due to Delphi limitation. Anyone knows a way to pass different records to a function and recognize their type when needed, as we do with class: if x is TMyClass then TMyClass(x) ... ???

• ### Bitwise OR of constants

##### - by ryyst
While reading some documentation here, I came across this: unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents *comps = [gregorian components:unitFlags fromDate:date]; I have no idea how this works. I read up on the bitwise operators in C, but I do not understand how you can fit three (or more!) constants inside one int and later being able to somehow extract them back from the int? Digging further down the documentation, I also found this, which is probably related: typedef enum { kCFCalendarUnitEra = (1 << 1), kCFCalendarUnitYear = (1 << 2), kCFCalendarUnitMonth = (1 << 3), kCFCalendarUnitDay = (1 << 4), kCFCalendarUnitHour = (1 << 5), kCFCalendarUnitMinute = (1 << 6), kCFCalendarUnitSecond = (1 << 7), kCFCalendarUnitWeek = (1 << 8), kCFCalendarUnitWeekday = (1 << 9), kCFCalendarUnitWeekdayOrdinal = (1 << 10), } CFCalendarUnit; How do the (1 << 3) statements / variables work? I'm sorry if this is trivial, but could someone please enlighten me by either explaining or maybe posting a link to a good explanation? Thanks! -- ry

• ### What are the default return values for operator< and operator[] in C++ (Visual Studio 6)?

##### - by DustOff
I've inherited a large Visual Studio 6 C++ project that needs to be translated for VS2005. Some of the classes defined operator< and operator[], but don't specify return types in the declarations. VS6 allows this, but not VS2005. I am aware that the C standard specifies that the default return type for normal functions is int, and I assumed VS6 might have been following that, but would this apply to C++ operators as well? Or could VS6 figure out the return type on its own? For example, the code defines a custom string class like this: class String { char arr; public: operator<(const String& other) { return something1 < something2; } operator[](int index) { return arr[index]; } }; Would VS6 have simply put the return types for both as int, or would it have been smart enough to figure out that operator[] should return a char and operator< should return a bool (and not convert both results to int all the time)? Of course I have to add return types to make this code VS2005 C++ compliant, but I want to make sure to specify the same type as before, as to not immediately change program behavior (we're going for compatibility at the moment; we'll standardize things later).

• ### C++ Operator Ambiguity

##### - by Scott
Forgive me, for I am fairly new to C++, but I am having some trouble regarding operator ambiguity. I think it is compiler-specific, for the code compiled on my desktop. However, it fails to compile on my laptop. I think I know what's going wrong, but I don't see an elegant way around it. Please let me know if I am making an obvious mistake. Anyhow, here's what I'm trying to do: I have made my own vector class called Vector4 which looks something like this: class Vector4 { private: GLfloat vector; ... } Then I have these operators, which are causing the problem: operator GLfloat* () { return vector; } operator const GLfloat* () const { return vector; } GLfloat& operator [] (const size_t i) { return vector[i]; } const GLfloat& operator [] (const size_t i) const { return vector[i]; } I have the conversion operator so that I can pass an instance of my Vector4 class to glVertex3fv, and I have subscripting for obvious reasons. However, calls that involve subscripting the Vector4 become ambiguous to the compiler: enum {x, y, z, w} Vector4 v(1.0, 2.0, 3.0, 4.0); glTranslatef(v[x], v[y], v[z]); Here are the candidates: candidate 1: const GLfloat& Vector4:: operator[](size_t) const candidate 2: operator[](const GLfloat*, int) <built-in> Why would it try to convert my Vector4 to a GLfloat* first when the subscript operator is already defined on Vector4? Is there a simple way around this that doesn't involve typecasting? Am I just making a silly mistake? Thanks for any help in advance.

• ### How can I override list methods to do vector addition and subtraction in python?

##### - by Bobble
I originally implemented this as a wrapper class around a list, but I was annoyed by the number of operator() methods I needed to provide, so I had a go at simply subclassing list. This is my test code: class CleverList(list): def __add__(self, other): copy = self[:] for i in range(len(self)): copy[i] += other[i] return copy def __sub__(self, other): copy = self[:] for i in range(len(self)): copy[i] -= other[i] return copy def __iadd__(self, other): for i in range(len(self)): self[i] += other[i] return self def __isub__(self, other): for i in range(len(self)): self[i] -= other[i] return self a = CleverList([0, 1]) b = CleverList([3, 4]) print('CleverList does vector arith: a, b, a+b, a-b = ', a, b, a+b, a-b) c = a[:] print('clone test: e = a[:]: a, e = ', a, c) c += a print('OOPS: augmented addition: c += a: a, c = ', a, c) c -= b print('OOPS: augmented subtraction: c -= b: b, c, a = ', b, c, a) Normal addition and subtraction work in the expected manner, but there are problems with the augmented addition and subtraction. Here is the output: >>> CleverList does vector arith: a, b, a+b, a-b = [0, 1] [3, 4] [3, 5] [-3, -3] clone test: e = a[:]: a, e = [0, 1] [0, 1] OOPS: augmented addition: c += a: a, c = [0, 1] [0, 1, 0, 1] Traceback (most recent call last): File "/home/bob/Documents/Python/listTest.py", line 35, in <module> c -= b TypeError: unsupported operand type(s) for -=: 'list' and 'CleverList' >>> Is there a neat and simple way to get augmented operators working in this example?

• ### Dilemma with two types and operator +

##### - by user35443
I have small problem with operators. I have this code: public class A { public string Name { get; set; } public A() { } public A(string Name) { this.Name = Name; } public static implicit operator B(A a) { return new B(a.Name); } public static A operator+(A a, A b) { return new A(a.Name + " " + b.Name); } } public class B { public string Name { get; set; } public B() { } public B(string Name) { this.Name = Name; } public static implicit operator A(B b) { return new A(b.Name); } public static B operator +(B b, B a) { return new B(b.Name + " " + a.Name); } } Now I want to know, which's conversion operator will be called and which's addition operator will be called in this operation: new A("a") + new B("b"); Will it be operator of A, or of B? (Or both?) Thanks....

• ### Dojo Datagrid Filtering Issue

##### - by Zoom Pat
I am having hard time filtering a datagrid. Please help! This is how I draw a grid. var jsonStore = new dojo.data.ItemFileWriteStore({data:columnValues}); gridInfo = { store: jsonStore, queryOptions: {ignoreCase: true}, structure: layout }; grid = new dojox.grid.DataGrid(gridInfo, "gridNode"); grid.startup(); Now if i try something like this, it works fine and gives me the rows which has the column (AGE_FROM) value equal to 63. grid.filter({AGE_FROM:63}); but I need all kinds of filtering and not just 'equal to' So how do I try to obtain all the rows which have AGE_FROM 63, and < 63 and <= 63 and =63. because grid.filter({AGE_FROM:<63}); does not work Also One other way I was thingking was to use the following filteredStore = new dojox.jsonPath.query(filterData,"[?(@.AGE_FROM = 63]"); and then draw the grid with the filteredStore, but the above is not working for a != operator. Once I figure a good way to filter grid I need to see a way to filter out dates. I am trying to find a good example for filtering dataGrid but most of the examples are just filtering based on the 'equal to' criteria. Any help is highly appreciated.

• ### What does the caret operator in Python do?

##### - by Fry
I ran across the caret operator in python today and trying it out, I got the following output: >>> 8^3 11 >>> 8^4 12 >>> 8^1 9 >>> 8^0 8 >>> 7^1 6 >>> 7^2 5 >>> 7^7 0 >>> 7^8 15 >>> 9^1 8 >>> 16^1 17 >>> 15^1 14 >>> It seems to be based on 8, so I'm guessing some sort of byte operation? I can't seem to find much about this searching sites other than it behaves oddly for floats, does anybody have a link to what this operator does or can you explain it here?

• ### How can I repeat a string in Perl?

##### - by izb
In Python, if I do this: print "4" * 4 I get > "4444" In Perl, I'd get > 16 Is there an easy way to do the former in Perl?

• ### operator for enums

##### - by Veer
Hi all, Just out of curiosity, asking this Like the expression one below a = (condition) ? x : y; // two outputs why can't we have an operator for enums? say, myValue = f ??? fnApple() : fnMango() : fnOrange(); // no. of outputs specified in the enum definition instead of switch statements (eventhough refractoring is possible) enum Fruit { apple, mango, orange }; Fruit f = Fruit.apple; Or is it some kind of useless operator?

• ### Usage of ||, OR in PHP

##### - by shin
I have the following code which redirect pages depends on \$path. ... \$path = \$this->uri->segment(3); \$pathid = \$this->uri->segment(4); if(\$path=='forsiden'){ redirect('','refresh'); }elseif(\$path =='contact'){ redirect('welcome/kontakt','refresh'); }elseif(\$path =='illustration'){ \$this->_gallery(\$path,\$pathid); }elseif(\$path =='webdesign'){ redirect('welcome/webdesign','refresh'); }elseif(\$path==('web_tjenester' || 'webdesigndetails' || 'vismahjemmeside' || 'joomla' || 'vismanettbutikk' || 'vpasp' || 'artportfolio')){ ... CODE A ... }else{ ... CODE B ... } I am not getting right results with \$path==('web_tjenester' || 'webdesigndetails' || 'vismahjemmeside' || 'joomla' || 'vismanettbutikk' || 'vpasp' || 'artportfolio') contact, illustration, gallery and webdesign are redirected and working alright. However all other pages are added CODE A. I am expecting CODE A only when \$path is web_tjenester', 'webdesigndetails', 'vismahjemmeside', 'joomla', 'vismanettbutikk', 'vpasp' or 'artportfolio'. Could anyone point out my mistake and correct me please? Thanks in advance. --UPDATE-- The following works, but is there any ways shorten the code? I am repeating (\$path==..). elseif((\$path=='web_tjenester') || (\$path=='webdesigndetails') || (\$path=='vismahjemmeside') || (\$path=='joomla') || (\$path=='vismanettbutikk') || (\$path=='vpasp') || (\$path=='artportfolio')){

• ### Rounding down DECIMAL(14,3) to thrid decimal digit in SQL 2008

##### - by abatishchev
I have to round down all incoming data with type DECIMAL(14,3) which has 3 decimal digit to the last one. I.e.: 100; 100.0; 100.00; 100.000 -> 100 100.2; 100.02; 100.20; 100.22 -> 100.xx but 100.221 -> 100.22 100.229 -> 100.22 Using which SQL operator can I check that residue of division in decimal digit is greater then zero?

• ### Python Ternary Operator

##### - by koldfyre
I was under the impression that Python had a ternary operator... But then I did some research, Not enough to find out for sure though Thought I'd ask the professionals ;)

• ### Is there an "opposite" to the null coalescing operator? (…in any language?)

##### - by Jay
null coalescing translates roughly to return x, unless it is null, in which case return y I often need return null if x is null, otherwise return x.y I can use return x == null ? null : x.y; Not bad, but that null in the middle always bothers me -- it seems superfluous. I'd prefer something like return x :: x.y;, where what follows the :: is evaluated only if what precedes it is not null. I see this as almost an opposite to null coalescence, kind of mixed in with a terse, inline null-check, but I'm [almost] certain that there is no such operator in C#. Are there other languages that have such an operator? If so, what is it called? (I know that I can write a method for it in C#; I use return NullOrValue.of(x, () => x.y);, but if you have anything better, I'd like to see that too.)

• ### Null-coalescing operator and operator && in C#

##### - by abatishchev
Is it possible to use together any way operator ?? and operator && in next case: bool? Any { get { var any = this.ViewState["any"] as bool?; return any.HasValue ? any.Value && this.SomeBool : any; } } This means next: if any is null then this.Any.HasValue return false if any has value, then it returns value considering another boolean property, i.e. Any && SomeBool

• ### What do you think about ??= operator in C#?

##### - by TN
Do you think that C# will support something like ??= operator? Instead of this: if (list == null) list = new List<int>(); It might be possible to write: list ??= new List<int>(); Now, I could use (but it seems to me not well readable): list = list ?? new List<int>();

• ### null coalescing operator for javascript?

##### - by Daniel Schaffer
I assumed this question has already been asked here, but I couldn't find any, so here it goes: Is there a null coalescing operator in Javascript? For example, in C#, I can do this: String someString = null; var whatIWant = someString ?? "Cookies!"; The best approximation I can figure out for Javascript is using the conditional operator: var someString = null; var whatIWant = someString ? someString : 'Cookies!'; Which is sorta icky IMHO. Can I do better?