with creating table in table in Lua C-API - lua

I use this code for creating table in table (Like namespace) in Lua C-API:
JNIEXPORT void JNICALL Java_com_naef_jnlua_LuaState_lua_1import_1tables(JNIEnv *env,
jobject obj, jstring namespace) {
lua_State *L;
JNLUA_ENV(env);
L = getluathread(obj);
char * str= getstringchars(namespace);
char ** res = NULL;
char * p = strtok (str, ".");
int n_spaces = 0, i;
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1);
res[n_spaces-1] = p;
p = strtok (NULL, ".");
}
for (i = 0; i < (n_spaces); ++i) {
if (i == 0) {
lua_newtable(L);
} else if (i == (n_spaces - 1)) {
lua_pushlstring(L, res[i], (sizeof(res[i])/sizeof(char))-1);
lua_getglobal(L, res[i]);
break;
} else {
lua_pushlstring(L, res[i], (sizeof(res[i])/sizeof(char))-1);
lua_newtable(L);
}
}
for (i = (n_spaces - 2); i >= 0 ; i--) {
if (i == 0) {
lua_setglobal(L, res[i]);
break;
} else {
lua_settable(L, -3);
}
}
free(res);
}
This is can be equals for this hardcode:
lua_newtable( L ); /* ==> stack: ..., {} */
{
lua_pushliteral( L, "b" ); /* ==> stack: ..., {}, "b" */
lua_newtable( L ); /* ==> stack: ..., {}, "b", {} */
{
lua_pushliteral( L, "c" ); /* == stack: ..., {}, "b", {}, "c" */
lua_newtable( L ); /* ==> stack: ..., {}, "b", {}, "c", {} */
{
lua_pushliteral( L, "d" );
lua_getglobal(L, "MyTable");
lua_settable( L, -3 );
}
lua_settable( L, -3 ); /* ==> stack: ..., {}, "b", {} */
}
lua_settable( L, -3 ); /* ==> stack: ..., {} */
}
lua_setglobal( L, "a" ); /* ==> stack: ... */
When i send i function Java_com_naef_jnlua_LuaState_lua_1import_1tables() String looks like this "com.naef.jnlua.test.fixture.TestObject"// TestObject is equivalent "MyTable", other like "com" tables in tables and TestObject table - the last table
When i try after this code execute lua code com.naef.jnlua.test.fixture.TestObject
attempt to index field 'naef' (a nil value)
Where i mistake?

Related

Why is the containsKey() function not detecting the repeated char as the key in Dart in the problem below?

The containsKey() function is not detecting the repeated value in my test 'current' string, where it just replaces the original value of the key 'r' with 3, when it should go through the containsKey() function, as see that there is a value at 2, and then replace that key with a new one.
void main(){
Map<String, String> split = new Map();
var word = 'current ';
for (int i = 0; i < word.length; i++) {
String temp = word[i];
if (split.containsKey([temp])) {
split[temp] = split[temp]! + ' ' + i.toString();
} else {
split[temp] = i.toString();
}
}
print(split.toString());
}
The output produces
{c: 0, u: 1, r: 3, e: 4, n: 5, t: 6}
while I want it to produce {c: 0, u: 1, r: 2 3, e: 4, n: 5, t: 6}
It is because you are doing split.containsKey([temp]) instead of split.containsKey(temp).
In your snippet, you are checking whether the map split has the array [temp] as a key, (in the case of 'r': ['r']), which is false, it has 'r' as a key, not ['r'].
Change your code to
void main(){
Map<String, String> split = new Map();
var word = 'current ';
for (int i = 0; i < word.length; i++) {
String temp = word[i];
if (split.containsKey(temp)) { // <- Change here.
split[temp] = split[temp]! + ' ' + i.toString();
} else {
split[temp] = i.toString();
}
}
print(split.toString());
}

General insertion sort algorithm not moving the first object in list

I need to create a general insertion sort algorithm using move semantics. I have it working for entire lists of different types of objects except for the very first object in the list.
template<typename Iter, typename Comparator>
void insertionSort(const Iter& begin, const Iter& end, Comparator compareFn)
{
for (auto i = begin + 1; i < end; i++)
{
auto currentthing = std::move(*i);
auto j = std::move(i - 1);
while (j >= begin and compareFn(*j, currentthing))
{
*(j + 1) = std::move(*j);
if (j == begin)
break;
j--;
}
*(j + 1) = std::move(currentthing);
}
}
Where comparing a list of strings from my main function:
int main()
{
vector<int> numbers = { 0, 1, 8, 4, 2, 9, 5, 3, 6, 7, 10 };
insertionSort(numbers.begin(), numbers.end(), std::less<int>());
cout << "Sorted: " << numbers << "\n";
vector<string> names = { "p", "a", "b", "d", "c", "f", "e" };
insertionSort(names.begin(), names.end(), std::greater<string>());
cout << "Sorted: " << names << "\n";
return 0;
}
Outputs the following
Sorted: [ 0 10 9 8 7 6 5 4 3 2 1 ]
Sorted: [ a b c d e f ]
The while loop should break when j equals i and not when j equals begin. So, the following:
if (j == begin)
break;
should actually be:
if (j == i)
break;

How does xv6 write to the terminal?

The printf function calls write (re. forktest.c):
void printf ( int fd, char *s, ... )
{
write( fd, s, strlen(s) );
}
Passing 1 as the fd writes to the console (as 1 maps to stdout). But where is write defined? I only see its declaration in user.h.
int write ( int, void*, int );
I'm assuming it somehow gets redirected to filewrite in file.c.
int filewrite (struct file *f, char *addr, int n )
{
int r;
if ( f->writable == 0 )
return -1;
if ( f->type == FD_PIPE )
return pipewrite( f->pipe, addr, n );
if ( f->type == FD_INODE )
{
// write a few blocks at a time to avoid exceeding
// the maximum log transaction size, including
// i-node, indirect block, allocation blocks,
// and 2 blocks of slop for non-aligned writes.
// this really belongs lower down, since writei()
// might be writing a device like the console.
int max = ( ( MAXOPBLOCKS - 1 - 1 - 2 ) / 2 ) * 512;
int i = 0;
while ( i < n )
{
int n1 = n - i;
if ( n1 > max )
n1 = max;
begin_op();
ilock( f->ip );
if ( ( r = writei( f->ip, addr + i, f->off, n1 ) ) > 0 )
f->off += r;
iunlock( f->ip );
end_op();
if ( r < 0 )
break;
if ( r != n1 )
panic( "short filewrite" );
i += r;
}
return i == n ? n : -1;
}
panic( "filewrite" );
}
And filewrite calls writei which is defined in fs.c.
int writei ( struct inode *ip, char *src, uint off, uint n )
{
uint tot, m;
struct buf *bp;
if ( ip->type == T_DEV )
{
if ( ip->major < 0 || ip->major >= NDEV || !devsw[ ip->major ].write )
return -1;
return devsw[ ip->major ].write( ip, src, n );
}
if ( off > ip->size || off + n < off )
return -1;
if ( off + n > MAXFILE*BSIZE )
return -1;
for ( tot = 0; tot < n; tot += m, off += m, src += m )
{
bp = bread( ip->dev, bmap( ip, off/BSIZE ) );
m = min( n - tot, BSIZE - off%BSIZE );
memmove( bp->data + off%BSIZE, src, m );
log_write( bp );
brelse( bp );
}
if ( n > 0 && off > ip->size )
{
ip->size = off;
iupdate( ip );
}
return n;
}
How does all this result in the terminal displaying the characters? How does the terminal know to read fd 1 for display, and where to find fd 1? What is the format of fd 1? Is it a standard?
Below is the full path from printf to the terminal. The gist is that eventually, xv6 writes the character to the CPU's serial port.
QEMU is initialized with the flags -nographic or -serial mon:stdio which tell it to use the terminal to send data to, or receive data from the CPU's serial port.
Step 1) printf in forktest.c
void printf ( int fd, const char *s, ... )
{
write( fd, s, strlen( s ) );
}
void forktest ( void )
{
...
printf( 1, "fork test\n" );
...
}
Step 2) write in usys.S
.globl write
write:
movl $SYS_write, %eax
int $T_SYSCALL
ret
Step 3) sys_write in sysfile.c
int sys_write ( void )
{
...
argfd( 0, 0, &f )
...
return filewrite( f, p, n );
}
static int argfd ( int n, int *pfd, struct file **pf )
{
...
f = myproc()->ofile[ fd ]
...
}
Previously during system initialization, main in init.c was called where the stdin (0), stdout (1), and stderr (2) file descriptors are created. This is what argfd finds when looking up the file descriptor argument to sys_write.
int main ( void )
{
...
if ( open( "console", O_RDWR ) < 0 )
{
mknod( "console", 1, 1 ); // stdin
open( "console", O_RDWR );
}
dup( 0 ); // stdout
dup( 0 ); // stderr
...
}
The stdin|out|err are inodes of type T_DEV because they are created using mknod in sysfile.c
int sys_mknod ( void )
{
...
ip = create( path, T_DEV, major, minor )
...
}
The major device number of 1 that is used to create them is mapped to the console. See file.h
// Table mapping major device number to device functions
struct devsw
{
int ( *read )( struct inode*, char*, int );
int ( *write )( struct inode*, char*, int );
};
extern struct devsw devsw [];
#define CONSOLE 1
Step 4) filewrite in file.c
int filewrite ( struct file *f, char *addr, int n )
{
...
if ( f->type == FD_INODE )
{
...
writei( f->ip, addr + i, f->off, n1 )
...
}
...
}
Step 5) writei in fs.c
int writei ( struct inode *ip, char *src, uint off, uint n )
{
...
if ( ip->type == T_DEV )
{
...
return devsw[ ip->major ].write( ip, src, n );
}
...
}
The call to devsw[ ip->major ].write( ip, src, n )
becomes devsw[ CONSOLE ].write( ip, src, n ).
Previously during system initialization, consoleinit mapped this to the function consolewrite (see console.c)
void consoleinit ( void )
{
...
devsw[ CONSOLE ].write = consolewrite;
devsw[ CONSOLE ].read = consoleread;
...
}
Step 6) consolewrite in console.c
int consolewrite ( struct inode *ip, char *buf, int n )
{
...
for ( i = 0; i < n; i += 1 )
{
consputc( buf[ i ] & 0xff );
}
...
}
Step 7) consoleputc in console.c
void consputc ( int c )
{
...
uartputc( c );
...
}
Step 8) uartputc in uart.c.
The out assembly instruction is used to write to the CPU's serial port.
#define COM1 0x3f8 // serial port
...
void uartputc ( int c )
{
...
outb( COM1 + 0, c );
}
Step 9) QEMU is configured to use the serial port for communication in the Makefile through the -nographic or -serial mon:stdio flags. QEMU uses the terminal to send data to the serial port, and to display data from the serial port.
qemu: fs.img xv6.img
$(QEMU) -serial mon:stdio $(QEMUOPTS)
qemu-nox: fs.img xv6.img
$(QEMU) -nographic $(QEMUOPTS)
fd==1 refers to stdout, or Standard Out. It's a common feature of Unix-like Operatin Systems. The kernel knows that it's not a real file. Writes to stdout are mapped to terminal output.

Google Sheet formula for cumulative sum with condition

I have a Google Sheet with the following layout:
Number | Counted? | Cumulative Total
4 | Y | 4
2 | | 6
9 | Y | 15
... | ... | ...
The first cell in the Cumulative Total column is populated with this formula:
=ArrayFormula((SUMIF(ROW(C2:C1000),"<="&ROW(C2:1000),C2:C1000)
However this counts all rows in the 'Number' column. How can I make the Cumulative Total only count rows where the Counted? cell is Y?
Try this in C2 and copy down:
= N(C1) + A2 * (B2 = "Y")
Update
Doesn't seem to work with SUMIFS, but there is a very slow matrix multiplication alternative:
=ArrayFormula(MMult((Row(2:1000)>=Transpose(Row(2:1000)))*Transpose(A2:A1000*(B2:B1000="Y")), Row(2:1000)^0))
Assuming "Number" in column A and "Counted?" in column B, try in C1
={"SUM"; ArrayFormula(if(ISBLANK(B2:B),,mmult(transpose(if(transpose(row(B2:B))>=row(B2:B), if(B2:B="Y", A2:A,0), 0)),row(B2:B)^0)))}
(Change ranges to suit).
Example
custom formula sample:
=INDEX(IF(B3:B="","", runningTotal(B3:B,1,,A3:A)))
sample file
source code
related
code:
/**
* Get running total for the array of numbers
* by makhrov.max#gmail.com
*
* #param {array} numbers The array of numbers
* #param {number} total_types (1-dafault) sum, (2) avg, (3) min, (4) max, (5) count;
* 1-d array or number
* #param {number} limit number of last values to count next time.
* Set to 0 (defualt) to take all values
* #param {array} keys (optional) array of keys. Function will group result by keys
* #return The hex-code of cell background & font color
* #customfunction
*/
function runningTotal(numbers, total_types, limit, keys) {
// possible types to return
var oTypes = {
'1': 'sum',
'2': 'avg',
'3': 'min',
'4': 'max',
'5': 'count'
}
// checks and defaults
var errPre = '🥴 ';
if( typeof numbers != "object" ) {
numbers = [ [numbers] ];
}
total_types = total_types || [1];
if( typeof total_types != "object" ) {
total_types = [ total_types ];
}
if( keys && typeof keys != "object" ) {
keys = [ [keys] ];
}
if (keys) {
if (numbers.length !== keys.length) {
throw errPre + 'Numbers(' +
numbers.length +
') and keys(' +
keys.length +
') are of different length'; }
}
// assign types
var types = [], type, k;
for (var i = 0; i < total_types.length; i++) {
k = '' + total_types[i];
type = oTypes[k];
if (!type) {
throw errPre + 'Unknown total_type = ' + k;
}
types.push(type);
}
limit = limit || 0;
if (isNaN(limit)) {
throw errPre + '`limit` is not a Number!';
}
limit = parseInt(limit);
// calculating running totals
var result = [],
subres = [],
nodes = {},
key = '-',
val;
var defaultNode_ = {
values: [],
count: 0,
sum: 0,
max: null,
min: null,
avg: null,
maxA: Number.MIN_VALUE,
maxB: Number.MIN_VALUE,
maxC: Number.MIN_VALUE,
minA: Number.MAX_VALUE,
minB: Number.MAX_VALUE,
minC: Number.MAX_VALUE
};
for (var i = 0; i < numbers.length; i++) {
val = numbers[i][0];
// find correct node
if (keys) { key = keys[i][0]; }
node = nodes[key] ||
JSON.parse(JSON.stringify(defaultNode_));
/**
* For findig running Max/Min
* sourse of algorithm
* https://www.geeksforgeeks.org
* /sliding-window-maximum-maximum-of-all-subarrays-of-size-k/
*/
// max
//reset first second and third largest elements
//in response to new incoming elements
if (node.maxA<val) {
node.maxC = node.maxB;
node.maxB = node.maxA;
node.maxA = val;
} else if (node.maxB<val) {
node.maxC = node.maxB;
node.maxB = val;
} else if (node.maxC<val) {
node.maxC = val;
}
// min
if (node.minA>val) {
node.minC = node.minB;
node.minB = node.minA;
node.minA = val;
} else if (node.minB>val) {
node.minC = node.minB;
node.minB = val;
} else if (node.minC>val) {
node.minC = val;
}
// if limit exceeds
if (limit !== 0 && node.count === limit) {
//if the first biggest we earlier found
//is matching from the element that
//needs to be removed from the subarray
if(node.values[0]==node.maxA) {
//reset first biggest to second and second to third
node.maxA = node.maxB;
node.maxB = node.maxC;
node.maxC = Number.MIN_VALUE;
if (val <= node.maxB) {
node.maxC = val;
}
} else if (node.values[0]==node.maxB) {
node.maxB = node.maxC;
node.maxC = Number.MIN_VALUE;
if (val <= node.maxB) {
node.maxC = val;
}
} else if (node.values[0]==node.maxC) {
node.maxC = Number.MIN_VALUE;
if (val <= node.maxB) {
node.maxC = val;
}
} else if(node.values[0]==node.minA) {
//reset first smallest to second and second to third
node.minA = node.minB;
node.minB = node.minC;
node.minC = Number.MAX_VALUE;
if (val > node.minB) {
node.minC = val;
}
}
if (node.values[0]==node.minB) {
node.minB = node.minC;
node.minC = Number.MAX_VALUE;
if (val > node.minB) {
node.minC = val;
}
}
if (node.values[0]==node.minC) {
node.minC = Number.MAX_VALUE;
if (val > node.minB) {
node.minC = val;
}
}
// sum
node.sum -= node.values[0];
// delete first value
node.values.shift();
// start new counter
node.count = limit-1;
}
// add new values
node.count++;
node.values.push(val);
node.sum += val;
node.avg = node.sum/node.count;
node.max = node.maxA;
node.min = node.minA;
// remember entered values for the next loop
nodes[key] = node;
// get the result depending on
// selected total_types
subres = [];
for (var t = 0; t < types.length; t++) {
subres.push(node[types[t]]);
}
result.push(subres);
}
// console.log(JSON.stringify(nodes, null, 4));
return result;
}

rewriting of Z3_ast during its traversing in C++

to_expr function leads to error. Could you advise what is wrong below?
context z3_cont;
expr x = z3_cont.int_const("x");
expr y = z3_cont.int_const("y");
expr ge = ((y==3) && (x==2));
ge = swap_tree( ge );
where swap_tree is a function that shall swap all operands of binary operations. It defined as follows.
expr swap_tree( expr e ) {
Z3_ast ee[2];
if ( e.is_app() && e.num_args() == 2) {
for ( int i = 0; i < 2; ++i ) {
ee[ 1 - i ] = swap_tree( e.arg(i) );
}
for ( int i = 0; i < 2; ++i ) {
cout <<" ee[" << i << "] : " << to_expr( z3_cont, ee[ i ] ) << endl;
}
return to_expr( z3_cont, Z3_update_term( z3_cont, e, 2, ee ) );
}
else
return e;
}
The problem is "referencing counting". A Z3 object can be garbage collected by the system if its reference counter is 0. The Z3 C++ API provides "smart pointers" (expr, sort, ...) for automatically managing the reference counters for us. Your code uses Z3_ast ee[2]. In the for-loop, you store the result of swap_tree(e.arg(0)) into ee[0]. Since the reference counter is not incremented, this Z3 object may be deleted when executing the second iteration of the loop.
Here is a possible fix:
expr swap_tree( expr e ) {
if ( e.is_app() && e.num_args() == 2) {
// using smart-pointers to store the intermediate results.
expr ee0(z3_cont), ee1(z3_cont);
ee0 = swap_tree( e.arg(0) );
ee1 = swap_tree( e.arg(1) );
Z3_ast ee[2] = { ee1, ee0 };
return to_expr( z3_cont, Z3_update_term( z3_cont, e, 2, ee ) );
}
else {
return e;
}
}

Resources