ActionScript 3 - What do these codes do? - actionscript-3

I'me trying to understand some Action Script 3 features in order to port some code.
Code 1
How does the "++" influences the index part mean? If idx_val=0 then what xvaluer index will be modified?
xvaluer(++idx_val) = "zero";
Code 2
Then I have this: what is the meaning of this part of code?
What is being assigned to bUnicode in the last 3 lines?
(can you explain me the "<<"s and ">>"s)
bUnicode = new Array(2);
i = (i + 1);
i = (i + 1);
bUnicode[0] = aData[(i + 1)] << 2 | aData[(i + 1)] >> 4;
i = (i + 1);
bUnicode[1] = aData[i] << 4 | aData[(i + 1)] >> 2;
Code 3
I haven't the faintest idea of what is happening here.
What is "as" ? What is the "?" ?
bL = c > BASELENGTH ? (INVALID) : (s_bReverseLPad[c]);
Code 4
What is "&&" ?
if ((i + 1) < aData.length && s_bReverseUPad(aData((i + 1))) != INVALID)
Code 5
What is "as" ? What is the "?" ?
n2 = c < 0 ? (c + 256) as (c)
bOut.push(n1 >> 2 & 63)
bOut.push((n1 << 4 | n2 >> 4) & 63)//What is the single "&" ?
bOut.push(n2 << 2 & 63)
Finally, what are the differences between "||" and "|", and between "=" and "==" ?

Code 1: ++i is almost the same thing as i++ or i += 1; The only real difference is that it's modified before it is evaluated. Read more here.
Code 2: << and >> are bitwise shifts, they literally shift bits by one place. You really need to understand Binary before you can mess about with these operators. I would recommend reading this tutorial all the way through.
Code 3: This one is called Ternary Operator and it's actually quite simple. It's a one line if / else statement. bL = c > BASELENGTH ? (INVALID) : (s_bReverseLPad[c]); is equivalent to:
if(c > BASELENGTH) {
bL = INVALID;
} else {
bL = s_bReverseLPad[c];
}
Read more about it here.
Code 4: "The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary." There is also the conditional-OR operator to keep in mind (||).
As an example of the AND operator here is some code:
if(car.fuel && car.wheels) car.move();
Read more about it here.
Code 5: From AS3 Reference: as "Evaluates whether an expression specified by the first operand is a member of the data type specified by the second operand." So basically you're casting one type to another, but only if it's possible otherwise you will get null.
& is Bitwise AND operator and | is Bitwise OR operator, again refer to this article.
= and == are two different operators. The former(=) is called Basic Assignment meaning it is used when you do any kind of assignment like: i = 3;. The later(==) is called Equal to and it is used to check if a value is equal to something else. if(i == 3) // DO STUFF;. Pretty straight forward.
The only part that doesn't make sense to me is the single question mark. Ternary Operator needs to have both ? and :. Does this code actually run for you? Perhaps a bit more context would help. What type is c?
n2 = c < 0 ? (c + 256) as (c)

Related

Divide algorithm for binary number with run time of O(logn)

I need to write in simple assembly language (not assembly syntax) a program that calculates the division of two binary numbers of 16 bits without a reminder in O(logn), and I wondered if there is an efficient algorithm to do it.
If found some algorithms on the web, but all of them are looking for access to specific bit in the number, and I can't do it..
The only arithmetic operations I have are +, -, shift right/left but only ones each operation, &, |, ! and thats all apparently..
Thanks,
Eliav
this should work.
does it help you?
C-Style:
c=1;
// find the maximum n for b*2^n <= a
// c=2^n
while((b << 1) <= a) {
b = b << 1;
c = c << 1;
}
while (c > 0) {
if (a - b >= 0) {
a -= b;
result += c;
}
c = c >> 1;
b = b >> 1;
}
Assembly-Style:
registers s0,s1,s2,s3, zero
syntax <instr.> <dest>,<src>,<arg>
%result: s0
%a: s1
%b: s2
%c: s3
add, s3, zero, 1
loop_1_start:
left_shift s4,s2,1
jump_if_greater s4,s1,loop_1_end
left_shift s2,s2,1
left_shift s3,s3,1
jump loop_1_start
loop_1_end:
loop_2_start:
jump_if_greate_or_equal s3,zero,loop_2_end
if_start:
sub s4,s1,s2
jump_if_smaller s4, zero, if_end
sub s1,s1,s2
add s0,s0,s3
if_end:
right_shift s2,s2,1
right_shift s3,s3,1
jump loop_2_start
loop_2_end:

What might cause "Undefined Behaviour" in this parallel GPU code?

Lets assume core1 and core2 try writing their variables a and b to same memory location.
How can UB be explained here?
We dont know if a or b is written to that memory location(as a last action).
We dont even know what is written there (a garbage)
Even the target memory address can be miscalculated(segfault?).
Some logical gates make wrong currents and CPU disables itself
CPU's frequency information becomes corrupt and goes high overclock(and break itself)
Can I assume only the first option is valid for all vendors of CPU( and GPU)?
I just converted below code into a parallel GPU code and it seems to be working fine.
Generic code:
for (j=0; j<YRES/CELL; j++) // this is parallelized
for (i=0; i<XRES/CELL; i++) // this is parallelized
{
r = fire_r[j][i];
g = fire_g[j][i];
b = fire_b[j][i];
if (r || g || b)
for (y=-CELL; y<2*CELL; y++)
for (x=-CELL; x<2*CELL; x++)
addpixel(i*CELL+x, j*CELL+y, r, g, b, fire_alpha[y+CELL][x+CELL]);
//addpixel accesses neighbour cells' informations and writes on them
//and makes UB
r *= 8;
g *= 8;
b *= 8;
for (y=-1; y<2; y++)
for (x=-1; x<2; x++)
if ((x || y) && i+x>=0 && j+y>=0 && i+x<XRES/CELL && j+y<YRES/CELL)
{
r += fire_r[j+y][i+x];
g += fire_g[j+y][i+x];
b += fire_b[j+y][i+x];
}
r /= 16;
g /= 16;
b /= 16;
fire_r[j][i] = r>4 ? r-4 : 0; // UB
fire_g[j][i] = g>4 ? g-4 : 0; // UB
fire_b[j][i] = b>4 ? b-4 : 0;
}
Opencl:
" int i=get_global_id(0); int j=get_global_id(1);"
" int VIDXRES="+std::to_string(kkVIDXRES)+";"
" int VIDYRES="+std::to_string(kkVIDYRES)+";"
" int XRES="+std::to_string(kkXRES)+";"
" int CELL="+std::to_string(kkCELL)+";"
" int YRES="+std::to_string(kkYRES)+";"
" int x=0,y=0,r=0,g=0,b=0,nx=0,ny=0;"
" r = fire_r[j*(XRES/CELL)+i];"
" g = fire_g[j*(XRES/CELL)+i];"
" b = fire_b[j*(XRES/CELL)+i];"
" int counterx=0;"
" if (r || g || b)"
" for (y=-CELL; y<2*CELL; y++){"
" for (x=-CELL; x<2*CELL; x++){"
" addpixel(i*CELL+x, j*CELL+y, r, g, b, fire_alpha[(y+CELL)*(3*CELL)+(x+CELL)],vid,vido);"
" }}"
" r *= 8;"
" g *= 8;"
" b *= 8;"
" for (y=-1; y<2; y++){"
" for (x=-1; x<2; x++){"
" if ((x || y) && i+x>=0 && j+y>=0 && i+x<XRES/CELL && j+y<YRES/CELL)"
" {"
" r += fire_r[(j+y)*(XRES/CELL)+(i+x)];"
" g += fire_g[(j+y)*(XRES/CELL)+(i+x)];"
" b += fire_b[(j+y)*(XRES/CELL)+(i+x)];"
" }}}"
" r /= 16;"
" g /= 16;"
" b /= 16;"
" fire_r[j*(XRES/CELL)+i] = (r>4 ? r-4 : 0);"
" fire_g[j*(XRES/CELL)+i] = (g>4 ? g-4 : 0);"
" fire_b[j*(XRES/CELL)+i] = (b>4 ? b-4 : 0);"
Here is picture of some rare artifacts of a 2D NDrangeKernel 's local boundary UB. Can these kill my GPU?
On xf86 and xf86_64 architectures it means We dont know if a or b is written to that memory location(as a last action), because load/store operations of 32 (for both) or 64 bit (xf86_64 only) memory aligned datatypes are atomic.
On other architectures usually We dont even know what is written there (a garbage) is a valid answer - for sure on RISC architectures, I currently don't know on GPU's.
Note that The fact the code works doesn't imply that it is correct and in the 99% of the times it's the source of sentences like "there's a compiler bug, the code was working until the previous version" or "the code works on the development machine. The server selected for production is broken" :)
EDIT:
On NVidia GPUs we have weakly-ordered memory model. In the description on the Cuda C Programming guide it's not explicitly stated that store operations are atomic. The write operations come from the same thread, so it does not mean that load/store operations are atomic.
For the code above, IMHO the first option is the only possible one. Basically, if you assume that you have enough threads/processors to execute all the loops in parallel, the inner nested loops (the x and y ones) will have undetermined values.
For example, if we consider only the
r += fire_r[j+y][i+x];
section, the value at fire_r[j+y][i+x] can be the original one just as well as the result of another instance of the same loop being finished in another thread.

Is it possible to use functions in Haskell parameters?

I have seen a few examples of Haskell code that use functions in parameters, but I can never get it to work for me.
example:
-- Compute the nth number of the Fibonacci Sequence
fib 0 = 1
fib 1 = 1
fib (n + 2) = fib (n + 1) + fib n
When I try this, it I get this error:
Parse error in pattern: n + 2
Is this just a bad example? Or do I have to do something special to make this work?
What you have seen is a special type of pattern matching called "n+k pattern", which was removed from Haskell 2010. See What are "n+k patterns" and why are they banned from Haskell 2010? and http://hackage.haskell.org/trac/haskell-prime/wiki/RemoveNPlusK
As Thomas mentioned, you can use View Patterns to accomplish this:
{-# LANGUAGE ViewPatterns #-}
fib 0 = 1
fib 1 = 1
fib ((subtract 2) -> n) = fib (n + 1) + fib n
Due to the ambiguity of - in this case, you'll need to use the subtract function instead.
I'll try to help out, being a total newbie in Haskell.
I believe that the problem is that you can't match (n + 2).
From a logical viewpoint, any argument "n" will never match "n+2", so your third rule would never be selected for evaluation.
You can either rewrite it, like Michael said, to:
fib n = fib (n - 1) + fib (n - 2)
or define the whole fibonnaci in a function using guards, something like:
fibonacci :: Integer -> Integer
fibonacci n
| n == 0 = 0
| (n == 1 || n == 2) = 1
| otherwise = fibonacci(n-1) + fibonacci(n-2)
The pattern matcher is limited to constructor functions. So while you can match the arguments of functions like (:) (the list constrcutor) or Left and Right (constructors of Either), you can't match arithmetic expressions.
I think the fib (n+2) = ... notation doesn't work and is a syntax error. You can use "regular expression" style matching for paramters, like lists or tuples:
foo (x:xs) = ...
where x is the head of the list and xs the remainder of the list or
foo (x:[]) =
which is matched if the list only has one element left and that is stored in x. Even complex matches like
foo ((n,(x:xs)):rg) = ...
are possible. Function definitions in haskell is a complex theme and there are a lot of different styles which can be used.
Another possibility is the use of a "switch-case" scheme:
foo f x | (f x) = [x]
foo _ _ = []
In this case, the element "x" is wrapped in a list if the condition (f x) is true. In the other cases, the f and x parameters aren't interesting and an empty list is returned.
To fix your problem, I don't think any of these are applicable, but why don't throw in a catch-remaining-parameter-values function definition, like:
fib n = (fib (n - 1)) + (fib (n - 2))
Hope this helps,
Oliver
Since (+) is a function, you can't pattern match against it. To do what you wanted, you'd need to modify the third line to read: fib n = fib (n - 1) + fib (n - 2).

Mysql Bitwise operations and filter

I try to implement a bitwise filter using MYSQL (with udf if needed)
The filter is something like a AND but I want to use the mask to build a new bit string...
Let me explain you with a sample :
Suppose I have a table with blob storing 8 bit streams:
data1: 10110110
data2: 01100010
data3: 00010011
Then I have a mask to apply to get the bits from data when mask value is 1
MASK: 00101011
And so get the following expected results:
data1: 1010
data2: 1010
data3: 0011
Is there a way to optimize the filtering, without looping on each bit of "mask" to get the corresponding value in "data" row...
CLARIFICATION
I've just taken 8 bits for the post, but it's more like 256 bytes
for Joe : To clarify the exemple, the mask 00101011 is interpreted as : get the bit value from data field at position 3,5,7,8, if you read the mask from left to right, enumerated from bit 1 to bit 8... Hope this clarification is "clear"...
You can use bitwise operators in MySQL:
http://dev.mysql.com/doc/refman/5.0/en/bit-functions.html
Example:
SELECT (data1 & b'00101011') as output1 FROM ......
Quick test:
SELECT (b'10110110' & b'00101011') as output1
This does a bitwise AND with the binary pattern of the mask you specified.
See the above link for more toys.
The only way I know of doing what you want is something like
SELECT ((data >> 2) & 8) | ((data >> 1) & 4) | (data & 3) FROM ...
Obviously, you'll have to construct the expression based on your mask; it's not very difficult to do, just a bit tedious — you basically need to loop over the bits in the mask, something like this:
var mask = 0b00101011;
var parts = new Array();
var shift = 0;
var unshift = 0;
while (mask > 0) {
while ((mask & 1) == 0) {
shift = shift + 1;
mask = mask >> 1;
}
submask = 0;
while ((mask & 1) == 1) {
submask = submask + (1 << unshift);
unshift = unshift + 1;
mask = mask >> 1;
}
parts.push( "((data >> " + shift + ") & " + submask + ")" );
}
var expr = parts.join( " | " );
console.log(expr);
The example code above is in JavaScript, so you can run it as a snippet here and get:
((data >> 0) & 3) | ((data >> 1) & 4) | ((data >> 2) & 8)
logged to the console, but it should be pretty easy to port to other languages.

How can I reverse the ON bits in a byte?

I was reading Joel's book where he was suggesting as interview question:
Write a program to reverse the "ON" bits in a given byte.
I only can think of a solution using C.
Asking here so you can show me how to do in a Non C way (if possible)
I claim trick question. :) Reversing all bits means a flip-flop, but only the bits that are on clearly means:
return 0;
What specifically does that question mean?
Good question. If reversing the "ON" bits means reversing only the bits that are "ON", then you will always get 0, no matter what the input is. If it means reversing all the bits, i.e. changing all 1s to 0s and all 0s to 1s, which is how I initially read it, then that's just a bitwise NOT, or complement. C-based languages have a complement operator, ~, that does this. For example:
unsigned char b = 102; /* 0x66, 01100110 */
unsigned char reverse = ~b; /* 0x99, 10011001 */
What specifically does that question mean?
Does reverse mean setting 1's to 0's and vice versa?
Or does it mean 00001100 --> 00110000 where you reverse their order in the byte? Or perhaps just reversing the part that is from the first 1 to the last 1? ie. 00110101 --> 00101011?
Assuming it means reversing the bit order in the whole byte, here's an x86 assembler version:
; al is input register
; bl is output register
xor bl, bl ; clear output
; first bit
rcl al, 1 ; rotate al through carry
rcr bl, 1 ; rotate carry into bl
; duplicate above 2-line statements 7 more times for the other bits
not the most optimal solution, a table lookup is faster.
Reversing the order of bits in C#:
byte ReverseByte(byte b)
{
byte r = 0;
for(int i=0; i<8; i++)
{
int mask = 1 << i;
int bit = (b & mask) >> i;
int reversedMask = bit << (7 - i);
r |= (byte)reversedMask;
}
return r;
}
I'm sure there are more clever ways of doing it but in that precise case, the interview question is meant to determine if you know bitwise operations so I guess this solution would work.
In an interview, the interviewer usually wants to know how you find a solution, what are you problem solving skills, if it's clean or if it's a hack. So don't come up with too much of a clever solution because that will probably mean you found it somewhere on the Internet beforehand. Don't try to fake that you don't know it neither and that you just come up with the answer because you are a genius, this is will be even worst if she figures out since you are basically lying.
If you're talking about switching 1's to 0's and 0's to 1's, using Ruby:
n = 0b11001100
~n
If you mean reverse the order:
n = 0b11001100
eval("0b" + n.to_s(2).reverse)
If you mean counting the on bits, as mentioned by another user:
n = 123
count = 0
0.upto(8) { |i| count = count + n[i] }
♥ Ruby
I'm probably misremembering, but I
thought that Joel's question was about
counting the "on" bits rather than
reversing them.
Here you go:
#include <stdio.h>
int countBits(unsigned char byte);
int main(){
FILE* out = fopen( "bitcount.c" ,"w");
int i;
fprintf(out, "#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n");
fprintf(out, "int bitcount[256] = {");
for(i=0;i<256;i++){
fprintf(out, "%i", countBits((unsigned char)i));
if( i < 255 ) fprintf(out, ", ");
}
fprintf(out, "};\n\n");
fprintf(out, "int main(){\n");
fprintf(out, "srand ( time(NULL) );\n");
fprintf(out, "\tint num = rand() %% 256;\n");
fprintf(out, "\tprintf(\"The byte %%i has %%i bits set to ON.\\n\", num, bitcount[num]);\n");
fprintf(out, "\treturn 0;\n");
fprintf(out, "}\n");
fclose(out);
return 0;
}
int countBits(unsigned char byte){
unsigned char mask = 1;
int count = 0;
while(mask){
if( mask&byte ) count++;
mask <<= 1;
}
return count;
}
The classic Bit Hacks page has several (really very clever) ways to do this, but it's all in C. Any language derived from C syntax (notably Java) will likely have similar methods. I'm sure we'll get some Haskell versions in this thread ;)
byte ReverseByte(byte b)
{
return b ^ 0xff;
}
That works if ^ is XOR in your language, but not if it's AND, which it often is.
And here's a version directly cut and pasted from OpenJDK, which is interesting because it involves no loop. On the other hand, unlike the Scheme version I posted, this version only works for 32-bit and 64-bit numbers. :-)
32-bit version:
public static int reverse(int i) {
// HD, Figure 7-1
i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
i = (i << 24) | ((i & 0xff00) << 8) |
((i >>> 8) & 0xff00) | (i >>> 24);
return i;
}
64-bit version:
public static long reverse(long i) {
// HD, Figure 7-1
i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L;
i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L;
i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL;
i = (i & 0x00ff00ff00ff00ffL) << 8 | (i >>> 8) & 0x00ff00ff00ff00ffL;
i = (i << 48) | ((i & 0xffff0000L) << 16) |
((i >>> 16) & 0xffff0000L) | (i >>> 48);
return i;
}
pseudo code..
while (Read())
Write(0);
I'm probably misremembering, but I thought that Joel's question was about counting the "on" bits rather than reversing them.
Here's the obligatory Haskell soln for complementing the bits, it uses the library function, complement:
import Data.Bits
import Data.Int
i = 123::Int
i32 = 123::Int32
i64 = 123::Int64
var2 = 123::Integer
test1 = sho i
test2 = sho i32
test3 = sho i64
test4 = sho var2 -- Exception
sho i = putStrLn $ showBits i ++ "\n" ++ (showBits $complement i)
showBits v = concatMap f (showBits2 v) where
f False = "0"
f True = "1"
showBits2 v = map (testBit v) [0..(bitSize v - 1)]
If the question means to flip all the bits, and you aren't allowed to use C-like operators such as XOR and NOT, then this will work:
bFlipped = -1 - bInput;
I'd modify palmsey's second example, eliminating a bug and eliminating the eval:
n = 0b11001100
n.to_s(2).rjust(8, '0').reverse.to_i(2)
The rjust is important if the number to be bitwise-reversed is a fixed-length bit field -- without it, the reverse of 0b00101010 would be 0b10101 rather than the correct 0b01010100. (Obviously, the 8 should be replaced with the length in question.) I just got tripped up by this one.
Asking here so you can show me how to do in a Non C way (if possible)
Say you have the number 10101010. To change 1s to 0s (and vice versa) you just use XOR:
10101010
^11111111
--------
01010101
Doing it by hand is about as "Non C" as you'll get.
However from the wording of the question it really sounds like it's only turning off "ON" bits... In which case the answer is zero (as has already been mentioned) (unless of course the question is actually asking to swap the order of the bits).
Since the question asked for a non-C way, here's a Scheme implementation, cheerfully plagiarised from SLIB:
(define (bit-reverse k n)
(do ((m (if (negative? n) (lognot n) n) (arithmetic-shift m -1))
(k (+ -1 k) (+ -1 k))
(rvs 0 (logior (arithmetic-shift rvs 1) (logand 1 m))))
((negative? k) (if (negative? n) (lognot rvs) rvs))))
(define (reverse-bit-field n start end)
(define width (- end start))
(let ((mask (lognot (ash -1 width))))
(define zn (logand mask (arithmetic-shift n (- start))))
(logior (arithmetic-shift (bit-reverse width zn) start)
(logand (lognot (ash mask start)) n))))
Rewritten as C (for people unfamiliar with Scheme), it'd look something like this (with the understanding that in Scheme, numbers can be arbitrarily big):
int
bit_reverse(int k, int n)
{
int m = n < 0 ? ~n : n;
int rvs = 0;
while (--k >= 0) {
rvs = (rvs << 1) | (m & 1);
m >>= 1;
}
return n < 0 ? ~rvs : rvs;
}
int
reverse_bit_field(int n, int start, int end)
{
int width = end - start;
int mask = ~(-1 << width);
int zn = mask & (n >> start);
return (bit_reverse(width, zn) << start) | (~(mask << start) & n);
}
Reversing the bits.
For example we have a number represented by 01101011 . Now if we reverse the bits then this number will become 11010110. Now to achieve this you should first know how to do swap two bits in a number.
Swapping two bits in a number:-
XOR both the bits with one and see if results are different. If they are not then both the bits are same otherwise XOR both the bits with XOR and save it in its original number;
Now for reversing the number
FOR I less than Numberofbits/2
swap(Number,I,NumberOfBits-1-I);