ActionScript/Flex: bitwise AND/OR over 32-bits - apache-flex

Question: Is there an easy way (library function) to perform a bitwise AND or OR on numbers larger than 32-bit in ActionScript?
From the docs:
"Bitwise operators internally manipulate floating-point numbers to change them into 32-bit integers. The exact operation performed depends on the operator, but all bitwise operations evaluate each binary digit (bit) of the 32-bit integer individually to compute a new value."
Bummer...
I can't use the & or | ops - does AS expose a library function to do this for Numbers?
Specifics: I'm porting a bunch of java to flex and the java maintains a bunch of 'long' masks. I know that I can split the Java masks into two ints on the flex side. Since all of my mask manip is localized this won't be too painful. However, I'd like to keep the port as 1-1 as possible.
Any suggestions?
Thanks!

I think your most straightforward option is to break the masks, and if possible the data being masked, into two pieces. You're butting up against a feature gap, so no point in being tricky if you can help it. And if you don't need real BigNum support, best not to even consider it.

If you don't mind porting some Javascript, Leemon Baird has written a public-domain Javascript library for handling big integers here:
http://www.leemon.com/crypto/BigInt.html
You won't be able to explicitly use the & and | operators, but you should be able to augment the existing code with bitwiseAnd and bitwiseOr methods.

`
public class NumberUtils
{
public static const MSB_CONV : Number = Math.pow(2, 32);
public static function bitwiseAND(num1 : Number, num2 : Number) : Number {
var msb1 : int = num1 / MSB_CONV;
var msb2 : int = num2 / MSB_CONV;
return (msb1 & msb2) * MSB_CONV + (num1 & num2);
}
..OR..shiftRight..
}
`

According to http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_11.html, there are no 64-bit integers (signed or unsigned)...only 32-bit.
The Number type, as you mentioned above, has a 53-bit mantissa, which is too short for you.
I searched for a BigNum FLEX implementation, but couldn't find one.
I'm guessing that you will have to simulate this with either an array of ints or a class with a high and low int.
Good Luck,
Randy Stegbauer

public function readInt64():Number
{
var highInt:uint = bytes.readUnsignedInt();
var lowerInt:uint = bytes.readUnsignedInt();
return highInt * Math.pow(2,32) + lowerInt;
}
public function writeInt64(value:Number):void
{
this.writeUnsignedInt(int(value / 0xffffffff));
this.writeUnsignedInt(int(value));
}

Related

Peano numbers in Rust

I wanted to write a simple implementation of Peano numbers in Rust and it seems that I managed to get the basics working:
use self::Peano::*;
use std::ops::Add;
#[derive(Debug, PartialEq)]
enum Peano {
Zero,
Succ(Box<Peano>)
}
impl Add for Peano {
type Output = Peano;
fn add(self, other: Peano) -> Peano {
match other {
Zero => self,
Succ(x) => Succ(Box::new(self + *x))
}
}
}
fn main() {
assert_eq!(Zero + Zero, Zero);
assert_eq!(Succ(Box::new(Zero)) + Zero, Succ(Box::new(Zero)));
assert_eq!(Zero + Succ(Box::new(Zero)), Succ(Box::new(Zero)));
assert_eq!(Succ(Box::new(Zero)) + Succ(Box::new(Zero)), Succ(Box::new(Succ(Box::new(Zero)))));
assert_eq!(Succ(Box::new(Zero)) + Zero + Succ(Box::new(Zero)), Succ(Box::new(Succ(Box::new(Zero)))));
}
However, when I decided to take look at how it was implemented by others, I saw that noone decided to do it with an enum, but rather with structs and PhantomData (example 1, example 2).
Is there something wrong with my implementation? Is this because Zero and Succ are enum variants and not true types (so my implementation is not actual type arithmetic)? Or is it just preferable to do this the "mainstream" way due to difficulties that would occur if I expanded my implementation?
Edit: my struggles with implementing Peano numbers using structs can be seen here.
Your Peano numbers are on the level of values, which are used for computation when the program is running. This is fine for playing around but not very useful, because binary numbers like i32 are much more efficient.
The other implementations represent Peano numbers on the type level, where you currently can't use ordinary numbers. This allows to express types that depend on a number, for example arrays of a fixed size. The computations then take place when the compiler is inferring types.

Use and implementation of the binary `is` operator with simple types in D. (DLang)

In D, is there any difference between the binary is operator in the case
void * p;
if ( p is null ) { } // #1
using pointers, versus simply either
if ( ! p ) { } // #2a
or
if ( p == null ) { } // #2b
without the is operator? (DLang)
(I'm restricting this to simple scalar types, no aggregates or complex types. I am aware that with classes is simply compares their addresses, iirc.)
With type void*, like other plain pointers, there's no difference. There's also no difference with int, but there are differences with other types, including float, arrays (including strings), structs, and classes.
I suggest you always write what you mean with any type, so if you change the type later it will be ok. Use is for seeing if two references are the same. Use == for seeing if contents are the same. Avoid !p, unless perhaps p is known to be a plain bool type, since it has the most surprising behavior (it does cast(bool) which can call an overloaded opCast!bool on structs and classes, and does .ptr !is null on arrays, which opens the joy of null vs zero length arrays). Better to just say what you mean and keep the code explicitly readable and resilient against refactorings.

java 8: How to convert following code to functional?

Instead of using the for loop, how do I use the Stream API of Java 8 on array of booleans? How do I use methods such as forEach, reduce etc.?
I want to get rid of the two variables totalRelevant and retrieved which I am using to maintain state.
As in a lambda expression, we can only reference final variables from its lexical context.
import java.util.Arrays;
import java.util.List;
public class IRLab {
public static void main(String[] args) {
// predefined list of either document is relevant or not
List<Boolean> documentRelivency = Arrays.asList(true, false, true, true, false);
System.out.println("Precision\tRecall\tF-Measure");
// variables for output
double totalRelevant = 0.0;
double retrieved = 0.0;
for (int i = 0; i < documentRelivency.size(); ++i) {
Boolean isRelevant = documentRelivency.get(i);
// check if document is relevant
if (isRelevant) totalRelevant += 1;
// total number of retrieved documents will be equal to
// number of document being processed currently, i.e. retrieved = i + 1
retrieved += 1;
// storing values using formulas
double precision = totalRelevant / retrieved;
double recall = totalRelevant / totalRelevant;
double fmeasure = (2 * precision * recall) / (precision + recall);
// Printing the final calculated values
System.out.format("%9.2f\t%.2f\t%.2f\t\n", precision, recall, fmeasure);
}
}
}
How do I convert above code to functional code using the Java 8 Stream API and Lambda Expressions? I need to maintain state for two variables as above.
Generally, converting imperative to a functional code will only be an improvement when you manage to get rid of mutable state that causes the processing of one element to depend on the processing of the previous one.
There are workarounds that allow you to incorporate mutable state, but you should first try to find a different representation of your problem that works without. In your example, the processing of each element depends on two values, totalRelevant and retrieved. The latter is just an ascending number and therefore can be represented as a range, e.g. IntStream.range(startValue, endValue). The second stems from your list of boolean values and is the number of true value inside the sublist (0, retrieved)(inclusive).
You could recalculate that value without needing the previous value, but reiterating the list in each step could turn out to be expensive. So instead, collect your list into a single int number representing a bitset first, i.e. [true, false, true, true, false] becomes 0b_10110. Then, you can get the number of one bits using intrinsic operations:
List<Boolean> documentRelivency = Arrays.asList(true, false, true, true, false);
int numBits=documentRelivency.size(), bitset=IntStream.range(0, numBits)
.map(i -> documentRelivency.get(i)? 1<<(numBits-i-1): 0).reduce(0, (i,j) -> i|j);
System.out.println("Precision\tRecall\tF-Measure");
IntStream.rangeClosed(1, numBits)
.mapToObj(retrieved -> {
double totalRelevant = Integer.bitCount(bitset&(-1<<(numBits-retrieved)));
return String.format("%9.2f\t%.2f\t%.2f",
totalRelevant/retrieved, 1f, 2/(1+retrieved/totalRelevant));
})
.forEach(System.out::println);
This way, you have expressed the entire operation in a functional way where the processing of one element does not depend on the previous one. It could even run in parallel, though this would offer no benefit here.
If the list size exceeds 32, you have to resort to long, or java.util.BitSet for more than 64.
But the whole operation is more an example of how to change the thinking from “this is a number I increment in each iteration” to “I’m processing a continuous range of values” and from “this is a number I increment when the element is true” to “this is the count of true values in a range of this list”.
It's unclear why you need to change your code to lambdas. Currently it's quite short and lambdas will not make it shorter or cleaner. However if you really want, you may encapsulate your shared state in the separate object:
static class Stats {
private int totalRelevant, retrieved;
public void add(boolean relevant) {
if(relevant)
totalRelevant++;
retrieved++;
}
public double getPrecision() {
return ((double)totalRelevant) / retrieved;
}
public double getRecall() {
return 1.0; // ??? was totalRelevant/totalRelevant in original code
}
public double getFMeasure() {
double precision = getPrecision();
double recall = getRecall();
return (2 * precision * recall) / (precision + recall);
}
}
And use with lambda like this:
Stats stats = new Stats();
documentRelivency.forEach(relevant -> {
stats.add(relevant);
System.out.format("%9.2f\t%.2f\t%.2f\t\n", stats.getPrecision(),
stats.getRecall(), stats.getFMeasure());
});
Lambda is here, but not Stream API. Seems that involving Stream API for such problem is not very good idea as you need to output the intermediate states of mutable container which should be mutated strictly in given order. Well, if you desperately need Stream API, replace .forEach with .stream().forEachOrdered.

How to write median & mode calculation function based on the group in mariadb ? So that i can use it in the query itself

How to write median & mode calculation function based on the group in mariadb ? So that i can use it in the query itself. My mariadb version version is 5.5.
While querying when i am using partition by clause i am getting error ? Can anybody suggest me any solution.
I recently encountered the same (or rather a similar) problem. I have not solved it, yet, but I am advancing towards a solution, which I will draft here.
User defined functions (UDFs) are written in C or C++ and have to be compiled to a shared library (*.so for *nix-Systems and *.dll for Windows). They follow a certain convention, which can be found out about in the MySQL manual. I've chosen a general quantile Approach, for it can easily return the median.
my_bool quantile_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
INIT_BUFFER();
}
//the initialization for the *current group*
void quantile_clear(UDF_INIT *initid, char *is_null, char *error)
{
CLEAR_BUFFER();
num_elements=0;
ADD_TO_BUFFER(args);
num_elements++;
if(ISNAN(quantile_value))
quantile_value = GET_QUANTILE_VALUE(args); //should only be called once, for its assumed to be constant
}
//add groups item
void void quantile_add(UDF_INIT *initid, UDF_ARGS *args,
char *is_null, char *error)
{
ADD_TO_BUFFER(args);
num_elements++;
}
//very simple percentile calculation, may be flawed - just for presentation
double quantile(UDF_INIT *initid, UDF_ARGS *args,
char *is_null, char *error)
{
SORT_BUFFER();
return GET_BUFFER_AT(ROUNDDOWN(quantile_value * num_elements));
}
void quantile_deinit(UDF_INIT *initid)
{
CLEANUP();
}
To clarify the logic: MariaDB or MySQL first calls quantile_init in which all of your fancy initialization will take place (allocate buffers and so on). For each group that shall be aggregated the quantile_clear is called, in which you can reset the internal summary variables used and add the first value to the list. Now for each remaining row the quantile_add method is called, in which you would add the respective value. In the quantile function the quantile is calculated and returned.
After compilation as a shared library you can copy the file (libmylib.so/mylib.dll) to the plugins directory of your RDBS and load the function by calling
CREATE AGGREGATE FUNCTION quantile RETURNS REAL SONAME mylib
Now you should be able to use the function like
SELECT quantile(value, .5) FROM data GROUP BY category;
I've never undergone the whole procedure, hence all this information is of theoretical value, but according to the MySQL Manual it should work alike.

Define a new mathematical function in TCL using Tcl_CreateMathFunc

I use TCL 8.4 and for that version I need to add a new mathematical function into TCL interpreter by using TCL library function, particularly Tcl_CreateMathFunc. But I could not find a single example of how it can be done. Please could you write for me a very simple example, assuming that in the C code you have a Tcl_Interp *interp to which you should add a math function (say, a function that multiplies two double numbers).
I once did some alternative implementations of random number generators for Tcl and you can look at some examples at the git repository. The files in generic implement both a tcl command and a tcl math function for each PRNG.
So for instance in the Mersenne Twister implementation, in the package init function we add the new function to the interpreter by declaring
Tcl_CreateMathFunc(interp, "mt_rand", 1, (Tcl_ValueType *)NULL, RandProc, (ClientData)state);
this registers the C function RandProc for us. In this case the function takes no arguments but the seeding equivalent (srand) shows how to handle a single parameter.
/*
* A Tcl math function that implements rand() using the Mersenne Twister
* Pseudo-random number generator.
*/
static int
RandProc(ClientData clientData, Tcl_Interp *interp, Tcl_Value *args, Tcl_Value *resultPtr)
{
State * state = (State *)clientData;
if (! (state->flags & Initialized)) {
unsigned long seed;
/* This is based upon the standard Tcl rand() initializer */
seed = time(NULL) + ((long)Tcl_GetCurrentThread()<<12);
InitState(state, seed);
}
resultPtr->type = TCL_DOUBLE;
resultPtr->doubleValue = RandomDouble(state);
return TCL_OK;
}
Be aware that this is an API that is very unlikely to survive indefinitely (for reasons such as its weird types, inflexible argument handling, and the inability to easily use it from Tcl itself). However, here's how to do an add(x,y) with both arguments being doubles:
Registration
Tcl_ValueType types[2] = { TCL_DOUBLE, TCL_DOUBLE };
Tcl_CreateMathFunc(interp, "add", 2, types, AddFunc, NULL);
Implementation
static int AddFunc(ClientData ignored, Tcl_Interp *interp,
Tcl_Value *args, Tcl_Value *resultPtr) {
double x = args[0].doubleValue;
double y = args[1].doubleValue;
resultPtr->doubleValue = x + y;
resultPtr->type = TCL_DOUBLE;
return TCL_OK;
}
Note that because this API is always working with a fixed number of arguments to the function (and argument type conversions are handled for you) then the code you write can be pretty short. (Writing it to be type-flexible with TCL_EITHER — only permissible in the registration/declaration — makes things quite a lot more complex, and you really are stuck with a fixed argument count.)

Resources