Define a new mathematical function in TCL using Tcl_CreateMathFunc - math

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.)

Related

porting python class to Julialang

I am seeing that Julia explicitly does NOT do classes... and I should instead embrace mutable structs.. am I going down the correct path here?? I diffed my trivial example against an official flux library but cannot gather how do I reference self like a python object.. is the cleanest way to simply pass the type as a parameter in the function??
Python
# Dense Layer
class Layer_Dense
def __init__(self, n_inputs, n_neurons):
self.weights = 0.01 * np.random.randn(n_inputs, n_neurons)
self.biases = np.zeros((1, n_neurons))
def forward(self, inputs):
pass
My JuliaLang version so far
mutable struct LayerDense
num_inputs::Int64
num_neurons::Int64
weights
biases
end
function forward(layer::LayerDense, inputs)
layer.weights = 0.01 * randn(layer.num_inputs, layer.num_neurons)
layer.biases = zeros((1, layer.num_neurons))
end
The flux libraries version of a dense layer... which looks very different to me.. and I do not know what they're doing or why.. like where is the forward pass call, is it here in flux just named after the layer Dense???
source : https://github.com/FluxML/Flux.jl/blob/b78a27b01c9629099adb059a98657b995760b617/src/layers/basic.jl#L71-L111
struct Dense{F, M<:AbstractMatrix, B}
weight::M
bias::B
σ::F
function Dense(W::M, bias = true, σ::F = identity) where {M<:AbstractMatrix, F}
b = create_bias(W, bias, size(W,1))
new{F,M,typeof(b)}(W, b, σ)
end
end
function Dense(in::Integer, out::Integer, σ = identity;
initW = nothing, initb = nothing,
init = glorot_uniform, bias=true)
W = if initW !== nothing
Base.depwarn("keyword initW is deprecated, please use init (which similarly accepts a funtion like randn)", :Dense)
initW(out, in)
else
init(out, in)
end
b = if bias === true && initb !== nothing
Base.depwarn("keyword initb is deprecated, please simply supply the bias vector, bias=initb(out)", :Dense)
initb(out)
else
bias
end
return Dense(W, b, σ)
end
This is an equivalent of your Python code in Julia:
mutable struct Layer_Dense
weights::Matrix{Float64}
biases::Matrix{Float64}
Layer_Dense(n_inputs::Integer, n_neurons::Integer) =
new(0.01 * randn(n_inputs, n_neurons),
zeros((1, n_neurons)))
end
forward(ld::Layer_Dense, inputs) = nothing
What is important here:
here I create an inner constructor only, as outer constructor is not needed; as opposed in the Flux.jl code you have linked the Dense type defines both inner and outer constructors
in python forward function does not do anything, so I copied it in Julia (your Julia code worked a bit differently); note that instead of self one should pass an instance of the object to the function as the first argument (and add ::Layer_Dense type signature so that Julia knows how to correctly dispatch it)
similarly in Python you store only weights and biases in the class, I have reflected this in the Julia code; note, however, that for performance reasons it is better to provide an explicit type of these two fields of Layer_Dense struct
like where is the forward pass call
In the code you have shared only constructors of Dense object are defined. However, in the lines below here and here the Dense type is defined to be a functor.
Functors are explained here (in general) and in here (more specifically for your use case)

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.

Ada equivalent of local static variable from C/C++

I'm coming from C/C++ on embedded systems and all the time inside a function we use a static variable so that the value is retained throughout calls.
In Ada, it seems like this is only done with the equivalent of file-level static variables. Is there an Ada equivalent.
C++:
function Get_HW_Counter() {
static int count = 0;
return ++count;
}
Ada:??
Package level variables.
Note that packages are not necessarily at file level; you can even create and use a package local to a subprogram if you wish. One use of a package is to create an object and all the methods acting on it (singleton pattern); keeping all details of the object private.
If my understanding of C++ is not too rusty, a close equivalent would be:
package HW_Counter is
function Get_Next;
private
count : natural := 0; -- one way of initialising
-- or integer, allowing -ve counts for compatibility with C++
end HW_Counter;
and that's all the package's customer needs to see.
package body HW_Counter is
function Get_Next return natural is
begin
count := count + 1;
return count;
end Get_Next;
begin -- alternative package initialisation part
count := 0;
end HW_Counter;
And usage would typically be
C := HW_Counter.get_next;

In boost::python how to wrap an overrideable function which takes a container of pointers to C++ objects and returns a pointer to one of them?

I'm wrapping a C++ framework with boost::python and I need to make a C++ method overrideable in python. This is a hook method, which is needed by the framework and has a default implementation in C++, which iterates through a list (passed as parameter) and performs a choice. The problems arise because the choice is stated by returning a pointer to the chosen element (an iterator, in fact), but I can't find a way to return a C++ pointer as a result of a python function. Can anyone help?
Thanks
This is most certainly doable, but you don't really have enough details. What you really need to do is create a c++ function that calls your python function, proceses the python result and returns a c++ result. To paraphrase (let's assume I have a boost object called func that points to some python function that parses a string and returns an int):
using boost::python;
A* test(const std::string &foo) {
object module = import("mymodule");
object func = module.attr("myfunc");
// alternatively, you could set the function by passing it as an argument
// to a c++ function that you have wrapped
object result = func(foo);
int val = extract<int>(result);
return new A(val); // Assumes that you've wrapped A.
}
// file: https://github.com/layzerar/box2d-py/blob/master/python/world.cpp
struct b2ContactFilter_W: b2ContactFilter, wrapper<b2ContactFilter>
{
bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB)
{
override func = this->get_override("ShouldCollide");
if (func)
{
return func(ref(fixtureA), ref(fixtureB)); //ref is boost::ref
}
return b2ContactFilter::ShouldCollide(fixtureA, fixtureB);
}
bool ShouldCollideDefault(b2Fixture* fixtureA, b2Fixture* fixtureB)
{
return b2ContactFilter::ShouldCollide(fixtureA, fixtureB);
}
};
class_<b2ContactFilter_W, boost::noncopyable>("b2ContactFilter")
.def("ShouldCollide", &b2ContactFilter::ShouldCollide, &b2ContactFilter_W::ShouldCollideDefault)
;
Is this what you need ?

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

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));
}

Resources