Reflection library - call to RunStaticMethod returns error - basic4android

i am trying to call the MotionEvent.obtain Methode using the reflections library.
But so far i am not very successful. Everything i try results in the same error...
Here my code from a button-click:
Dim upTime As Long
Dim ev As Object
Dim args(12) As Object
Dim types(12) As String
upTime = Obj1.RunStaticMethod("android.os.SystemClock", "uptimeMillis", Null, Null)
'public static MotionEvent obtain (Long downTime, Long eventTime, Int action, Float x, Float y, Float pressure, Float size, Int metaState, Float xPrecision, Float yPrecision, Int deviceId, Int edgeFlags)
'Since: API Level 1
'Create a new MotionEvent, filling in all of the basic values that define the motion.
'Parameters:
'downTime The time (in ms) when the user originally pressed down To start a stream of position events. This must be obtained from uptimeMillis().
args(0) = upTime
types(0) = "java.lang.long"
'eventTime The the time (in ms) when this specific event was generated. This must be obtained from uptimeMillis().
args(1) = upTime
types(1) = "java.lang.long"
'action The kind of action being performed, such As ACTION_DOWN.
args(2) = "1" 'MotionEvent.ACTION_UP
types(2) = "java.lang.int"
'x The X coordinate of this event.
args(3) = "50.0"
types(3) = "java.lang.float"
'y The Y coordinate of this event.
args(4) = "20.0"
types(4) = "java.lang.float"
'pressure The current pressure of this event. The pressure generally ranges from 0 (no pressure at all) To 1 (normal pressure), however values higher than 1 may be generated depending on the calibration of the input device.
args(5) = "1.0"
types(5) = "java.lang.float"
'size A scaled value of the approximate size of the area being pressed when touched with the finger. The actual value in pixels corresponding To the finger touch Is normalized with a device specific range of values AND scaled To a value between 0 AND 1.
args(6) = "1.0"
types(6) = "java.lang.float"
'metaState The state of any meta / modifier keys that were in effect when the event was generated.
args(7) = "0"
types(7) = "java.lang.int"
'xPrecision The precision of the X coordinate being reported.
args(8) = "1.0"
types(8) = "java.lang.float"
'yPrecision The precision of the Y coordinate being reported.
args(9) = "1.0"
types(9) = "java.lang.float"
'deviceId The id For the device that this event came from. An id of zero indicates that the event didn't come from a physical device; other numbers are arbitrary and you shouldn't depend on the values.
args(10) = "0"
types(10) = "java.lang.int"
'edgeFlags A bitfield indicating which edges, If any, were touched by this MotionEvent.
args(11) = "0"
types(11) = "java.lang.int"
'call methode
***ev = Obj2.RunStaticMethod("android.view.MotionEvent", "obtain", args, types)***
Here the error occurs (java.lang.IllegalArgumentException: argument type mismatch):
10-09 09:02:26.951: ERROR/B4A(296): ev = Obj2.RunStaticMethod("android.view.MotionEvent", "obtain", args, types)
10-09 09:02:26.961: ERROR/B4A(296): java.lang.IllegalArgumentException: argument type mismatch
10-09 09:02:26.961: ERROR/B4A(296): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 09:02:26.961: ERROR/B4A(296): at java.lang.reflect.Method.invoke(Method.java:521)
10-09 09:02:26.961: ERROR/B4A(296): at anywheresoftware.b4a.agraham.reflection.Reflection.RunStaticMethod(Reflection.java:860)
10-09 09:02:26.961: ERROR/B4A(296): at anywheresoftware.b4a.agraham.reflectiondemo.main._button2_click(main.java:564)
10-09 09:02:26.961: ERROR/B4A(296): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 09:02:26.961: ERROR/B4A(296): at java.lang.reflect.Method.invoke(Method.java:521)
10-09 09:02:26.961: ERROR/B4A(296): at anywheresoftware.b4a.BA.raiseEvent2(BA.java:105)
10-09 09:02:26.961: ERROR/B4A(296): at anywheresoftware.b4a.BA.raiseEvent2(BA.java:93)
10-09 09:02:26.961: ERROR/B4A(296): at anywheresoftware.b4a.BA.raiseEvent(BA.java:89)
10-09 09:02:26.961: ERROR/B4A(296): at anywheresoftware.b4a.objects.ViewWrapper$1.onClick(ViewWrapper.java:49)
10-09 09:02:26.961: ERROR/B4A(296): at android.view.View.performClick(View.java:2408)
10-09 09:02:26.961: ERROR/B4A(296): at android.view.View$PerformClick.run(View.java:8816)
10-09 09:02:26.961: ERROR/B4A(296): at android.os.Handler.handleCallback(Handler.java:587)
10-09 09:02:26.961: ERROR/B4A(296): at android.os.Handler.dispatchMessage(Handler.java:92)
10-09 09:02:26.961: ERROR/B4A(296): at android.os.Looper.loop(Looper.java:123)
10-09 09:02:26.961: ERROR/B4A(296): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-09 09:02:26.961: ERROR/B4A(296): at java.lang.reflect.Method.invokeNative(Native Method)
10-09 09:02:26.961: ERROR/B4A(296): at java.lang.reflect.Method.invoke(Method.java:521)
10-09 09:02:26.961: ERROR/B4A(296): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-09 09:02:26.961: ERROR/B4A(296): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-09 09:02:26.961: ERROR/B4A(296): at dalvik.system.NativeStart.main(Native Method)
10-09 09:02:26.961: ERROR/B4A(296): java.lang.IllegalArgumentException: argument type mismatch
Dim args1(1) As Object
Dim types1(1) As String
args1(0) = ev
types1(0) = "android.view.MotionEvent"
Obj2.Target = Activity
Obj2.RunStaticMethod("android.view.View","dispatchTouchEvent",args1,types1)
Any help would be great...
Thank you,
Richard.

Did you see the Multitouch tutorial? Maybe the Gestures library already does what you need.
Anyway you can do it with this code:
Sub Activity_Create(FirstTime As Boolean)
Dim me As Object
me = ObtainMotionEvent(1000, 1000, 1, 100, 100, 500, 500, 0, 100, 100, 0, 0)
Log(me)
End Sub
Sub ObtainMotionEvent(DownTime As Long, EventTime As Long, Action As Int, _
X As Float, Y As Float, Pressure As Float, Size As Float, MetaState As Int, _
XPrecision As Float, YPrecision As Float, DeviceId As Int, EdgeFlags As Int) As Object
Dim r As Reflector
Dim f, i As String
f = "java.lang.float"
i = "java.lang.int"
l = "java.lang.long"
Return r.RunStaticMethod("android.view.MotionEvent", "obtain", _
Array As Object(DownTime, EventTime, Action, X, Y, Pressure, Size, MetaState, _
XPrecision, YPrecision, DeviceId, EdgeFlags), _
Array As String(l, l, i, f, f, f, f, i, f, f, i, i))
End Sub

Related

am getting this error :" RangeError (index): Invalid value: Only valid value is 0: 1"

am trying to solve some leetcode problems and kept getting this error , but when i run the code in another compiler it runs okey , this is the code :
class Solution {
double findMedianSortedArrays(List<int> nums1, List<int> nums2) {
double median = 0;
int m = nums1.length;
int n = nums2.length;
List<int> nums3 = [nums1, nums2].expand((x) => x).toList();
if ((m + n) % 2 == 0) {`your text`
int mid = (nums3.length / 2).toInt();
median = (nums3[mid] + nums3[mid - 1]) / 2;
return median;
} else {
int mid = (nums3.length / 2).ceil();
median = nums3[mid].toDouble();
return median;
}
}
}
this is the error:
Line 13: RangeError (index): Invalid value: Only valid value is 0: 1
#0 List.[] (dart:core-patch/growable_array.dart:264:36)
#1 Solution.findMedianSortedArrays (file:///solution.dart:13:21)
#2 main (file:///solution.dart:49:30)
<asynchronous suspension>
referring to this part => # median = nums3[mid].toDouble();
it should return the median of two sorted tables , but i keep getting this error
I can be wrong but in the use of [mid] you had a mid value of 1 when you did int mid = (nums3.length / 2).toInt(); it reached the result of 1, but the list was entirely empty (i.e. it was only []) causing the error.
You need to treat this exceptions however
I highly recommend checking other solutions like this one https://leetcode.com/problems/median-of-two-sorted-arrays/solutions/2651020/c-solution/ it wont cause the same issue. You must remember to consider errors and when empty results come

Cython/Armadillo error: scipy.sparse.csc_matrix to SpMat conversion

I'm currently wrapping the Armadillo library in Cython and have some trouble to convert scipy.sparse.csc_matrix in Python through Cython to the sparse matrix class from Armadillo.
The function to do so is actually like this :
cdef inline SpMat[double] * sp_to_spmatp(X):
cdef np.ndarray[int, ndim = 1, mode = 'c'] col_ptrs = X.indptr
cdef np.ndarray[int, ndim = 1, mode = 'c'] row_indices = X.indices
cdef np.ndarray[double, ndim = 1, mode = 'c'] values = X.data
cdef SpMat[double] *p_spRes = new SpMat[double](<int*> &row_indices[0], <int*> &col_ptrs[0], <double*> &values[0], X.shape[0], X.shape[1])
return p_spRes
where X is the sparse matrix from scipy and p_spRes the sparse matrix from Armadillo.
By building it I get this error:
arma_wrapper.cpp:3418:549: error: no matching function for call to
‘arma::SpMat::SpMat(int*, int*, double*, int&, int&)’
along with:
Armadillo/include/armadillo_bits/SpMat_bones.hpp:103:10: note: candidate: template<class T1, class T2, class T3> arma::SpMat<eT>::SpMat(const arma::Base<long long unsigned int, T1>&, const arma::Base<long long unsigned int, T2>&, const arma::Base<eT, T3>&, arma::uword, arma::uword)
inline SpMat(const Base<uword,T1>& rowind, const Base<uword,T2>& colptr, const Base<eT,T3>& values, const uword n_rows, const uword n_cols);
^~~~~
Armadillo/include/armadillo_bits/SpMat_bones.hpp:103:10: note: template argument deduction/substitution failed:
arma_wrapper.cpp:3418:549: note: mismatched types ‘const arma::Base<long long unsigned int, T1>’ and ‘int*’
].strides)))), ((double *)(&(*__Pyx_BufPtrCContig1d(__pyx_t_5numpy_double_t *, __pyx_pybuffernd_values.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_values.diminfo[0].strides)))), __pyx_t_10, __pyx_t_11);
^
which makes me think that some type casts may be incorrect.
If anyone does know anything about it, it will be greatly appreciated.

Reading the Fortran real data type into Matlab from a hex dump

As the title says I am writing a large amount of real arrays from Fortran into an unformatted file, and then trying to read that binary file into Matlab. I have successfully made my script work for strings and integers, but It does not correctly read my real numbers from the hex dump.
As a test case I was using the number 5.49. Interesting side note, according to an online converter that is 40 af ae 14, yet when I check my hexfile that portion of my code is reading 14 ae af 40. I have tried reading it in as a float32 and double, and I have changed fro neutral to little endian to big endian. Any ideas?
Here is a simple example of my code:
First the Fortran write statements
REAL :: floating = 5.49
open(unit = 2, file = "anxietySource", form = "unformatted", status = "new", action = "readwrite")
write(unit = 2 ) floating
Now the Matlab read statement
fid = fopen('anxietySource', 'rb');
h1 = fread(fid, 1, 'int32'); %this is just reading off the starter bits that tell me how long my write statement is
floating = fread(fid,1,'float32');
display(floating);
fclose(fid);
My guess is that there is something funky with the Fortran REAL type. Maybe it's not quite a floating point?
Good job on the bit level work getting this far, you are almost there.
"Big Endien versus little..."
https://gcc.gnu.org/onlinedocs/gfortran/CONVERT-specifier.html
http://www.lahey.com/docs/lfenthelp/F95ARINQUIREStmt.htm
https://software.intel.com/en-us/forums/intel-fortran-compiler-for-linux-and-mac-os-x/topic/270026
There is also manually shifting it https://www.nsc.liu.se/~boein/f77to90/a5.html#section10
MODULE Shifty
PRIVATE
INTERFACE Shift
MODULE PROCEDURE Shift4 !,Shift8
END INTERFACE
CONTAINS
REAL FUNCTION Shift4(MyFloat)
IMPLICIT NONE
REAL, INTENT(IN) :: MyFloat
INTEGER*4 :: Float1
INTEGER*4 :: Float2
INTEGER*4 :: Float3
INTEGER*4 :: Float4
INTEGER*4 :: MyInt
EQUIVALENCE(MyInt, MyFloat)
INTEGER*4 :: MyIntOut
EQUIVALENCE(MyIntOut, Shift4)
WRITE(*,20) MyInt
20 FORMAT('Incoming Real=',1PE12.5,' ==",Z8.8,'"')
Float1 = IBITS(MyInt, 0, 8)
Float2 = IBITS(MyInt, 8, 8)
Float3 = IBITS(MyInt,16, 8)
Float4 = IBITS(MyInt,24, 8)
WRITE(*,30) 1, Float1 !Check
WRITE(*,30) 2, Float2
WRITE(*,30) 3, Float3
WRITE(*,30) 4, Float4
30 FORMAT('Float',I1,'="',Z2.2,'"')
Float1 = ISHFT(Float1, 24)
Float2 = ISHFT(Float2, 16)
Float3 = ISHFT(Float3, 8)
Float4 = ISHFT(Float4, 0)
MyIntOut = IOR(Float1 , Float2)
MyIntOut = IOR(MyIntOut, Float3)
MyIntOut = IOR(MyIntOut, Float4)
WRITE(*,20) MyInt, MyIntOut
20 FORMAT('Incoming Real="',Z8.8,' Outgoing="',Z8.8,'"')
RETURN
END FUNCTION Shift4
END MODULE Shifty
PROGRAM MAT2F90
USE Shifty
IMPLICIT NONE
TYPE MATLAB_HEADER
CHARACTER(LEN=120) :: Descriptor !should be 116 and INT*8 !!
INTEGER*4 :: Offset
INTEGER*2 :: Version
CHARACTER(LEN=2) :: Endien
END TYPE MATLAB_HEADER
TYPE MATLAB_SUBHEADER
INTEGER*4 :: Type
INTEGER*4 :: Bytes
END TYPE MATLAB_SUB_HEADER
TYPE(MATLAB_HEADER) :: Head
TYPE(MATLAB_SUB_HEADER),DIMENSION(20) :: Tag
CHARACTER(LEN=12), DIMENSION(18) :: Matlab_Version = RESHAPE(&
['miINT8 ','miUINT8 ','miINT16 ','miUINT16 ', &
'miINT32 ','miUINT32 ','miSINGLE ','Reserved ', &
'miDOUBLE ','Reserved ','Reserved ','miINT64 ', &
'miUINT64 ','miMATRIX ','miCOMPRESSED','miUTF8 ', &
'miUTF16 ','miUTF32 '],[18])
LOGICAL :: Swap
...
OPEN(UNIT=22,FILE='<somename>',ACCESS='STREAM',FORM='UNFORMATTED',IOSTAT=Status)
IF(Status =/0 ) ...Do something
READ(20,IOSTAT=Status) Head
IF(Status =/0 ) ...Do something
WRITE(*,*)'Head.Descriptor="',Head.Descriptor,'"'
WRITE(*,*)'Head.Offset = ',Head.Offset
WRITE(*,*)'Head.Version = ',Head.Version
WRITE(*,*)'Head.Endien ="',Head.Endian,'"'
IF(Head.Endian == 'IM') THEN
SWAP = .FALSE.
ELSEIF(Head.Endian == 'MI') THEN
SWAP = .TRUE.
ELSE
WRITE(*,*)'Unknown Endien="',Head.Endian,'"'
STOP
ENDIF
READ(20,IOSTAT=Status) Tag(1)
IF(Status =/0 ) ...Do something
WRITE(*,*)'Tag(1).Type = ',Tag(1).Type,' == "',Matlab_Version(Tag(1).Type),'"'
WRITE(*,*)'Tag(1).Bytes= ',Tag(1).Bytes
!read and swap if need be...
!There is padding to an 8type boundary
!Read the next tag and data... etc
Section 1-5 to 1-9 https://data.cresis.ku.edu/data/mat_reader/matfile_format.pdf . You may notice like I did that type15 is 'miCOMPRESSED', so at that point one needs the uncompressor to make sense of it.
You'll need to test it like you did before, because it is easy for me to get the order wrong, and I am doing this by memory.(Updated as I was doing this today, but in a subroutine, so it should work as a function??)
I made it 4 in case you need an '8' version... And then you just call Shifty() and you can get the one that matches your data.

"Implicit Conversion Loses Integer Precision" error

I have this code and get the following error: Implicit Conversion Loses Integer Precision
size_t BitArray::wordsForBits(size_t bits) {
int arraySize = (bits + bitsPerWord_ - 1) >> logBits_;
return arraySize;
}
How can I resolve this?

Subroutine is returning NaN. Class variable issue?

I am having issues with a simple code I have written. subroutine energy is supposed to calculate the energy of the system, and is frequently returning NaN. The reason why it is doing that is because a value dd, distance between particles, is becoming zero and I have no idea why. I am relatively new to Fortran, and I believe maybe it has something to do with how I am passing class variables around which is why I came here. The code and modules are as follows.
module get started defines a class andreads values from an input file and prints to screen.
module get_started
implicit none
type input
integer :: np
integer :: istart
integer :: mceq,mcsteps
integer :: nsample, nadjust
double precision :: rcut,rcut2,rv,rv2,rcrv2
double precision :: maxd
double precision :: vol,box,hbox
double precision :: eps,sig
double precision :: dens
double precision :: temp
end type input
contains
subroutine init(param)
implicit none
type(input) :: param
open(unit=1,file='input')
read(1,*)param%rcut
read(1,*)param%np ! system's size
read(1,*)param%dens ! thermodynamical conditions
read(1,*)param%temp
read(1,*)param%istart
read(1,*)param%maxd
read(1,*)param%mceq,param%mcsteps
read(1,*)param%nsample
read(1,*)param%nadjust
param%eps = 1.0d0
param%sig = 1.0d0
param%rcut2 = param%rcut*param%rcut
param%rv = 1.1*param%rcut
param%rv2 = param%rv*param%rv
param%rcrv2 = (param%rv-param%rcut) * (param%rv-param%rcut)
param%vol = param%np/param%dens
param%box = param%vol**(1.0d0/3.0d0)
param%hbox = param%hbox/2
return
end subroutine init
subroutine print_input(param)
implicit none
type(input):: param
print*
print*,' A Monte Carlo program for Lennard-Jones particles'
print*,' -------------------------------------------------'
print*,' Lennard-Jones parameters:'
print*,' np=',param%np
print*,' eps= ',param%eps
print*,' sig= ',param%sig
print*,' rcut= ',param%rcut
print*,' rv =',param%rv
print*,' rv2 =',param%rv2
print*
print*,' Simulation box length: ',param%box
print*,' Volume : ',param%vol
print*,' Number density : ',param%dens
print*,' Temperature : ',param%temp
print*
print*
print*,' maxd : ',param%maxd
print*,' # eq steps : ',param%mceq
print*,' # MC steps : ',param%mcsteps
print*,' Sampling freq : ',param%nsample
print*,' Adjusting freq : ',param%nadjust
print*
return
end subroutine print_input
end module get_started
module position initializes the positions of the particles
module position
use get_started
implicit none
integer:: numpd
double precision ::gsize
integer :: i,j,k
integer :: flag
contains
subroutine init_position(param,x,y,z,flag)
implicit none
type(input),intent(in) :: param
double precision :: x(param%np),y(param%np),z(param%np)
integer :: counter,flag
numpd = ceiling(param%np**(1.0d0/3.0d0))
print*,'numpd',numpd
print*,'box',param%box
gsize = param%box/numpd
print*,'gsize',gsize
if(flag.eq.0) then
counter =1
do i=1,numpd
do j=1,numpd
do k=1,numpd
if(counter.le.param%np)then
y(counter) = i*gsize
z(counter) = j*gsize
x(counter) = k*gsize
endif
counter = counter+1
enddo
enddo
enddo
else if(flag.eq.1) then
do i=1,param%np
x(i) = ran()*param%box
y(i) = ran()*param%box
z(i) = ran()*param%box
enddo
end if
open(unit=2,file='posit.dat')
do i =1,param%np
write(2,*)x(i),y(i),z(i)
enddo
close(unit=2)
return
end subroutine init_position
end module position
module modmove_energy is where all the action is at. In this module, the subroutines which apply the monte carlo move (picking a particle, random displacement, and accepting or rejecting move) along with the energy calclulation (this is where the error is) are contained. It is the variable dd in energy which is returning zero for non identical particles frequently, and hence causing the NaN error.
module modmove_energy
use get_started
contains
! note random generator function
subroutine move(potential,param,x,y,z,ar)
implicit none
integer :: ar,it,step
type(input),intent(in) :: param
double precision :: potential
double precision :: x(param%np),y(param%np),z(param%np)
double precision :: xold,yold,zold,drxold,dryold,drzold
double precision :: dr2
double precision :: uold,unew,delta
double precision :: alpha,beta,gamma
it = int(ran()*param%np)+1
call energy(uold,x,y,z,param)
alpha =param%maxd*(ran()-0.5)
beta =param%maxd*(ran()-0.5)
gamma =param%maxd*(ran()-0.5)
x(it) = x(it) + alpha
y(it) = y(it) + beta
z(it) = z(it) + gamma
if (x(it) > param%box) then
x(it)=x(it)-param%box
elseif (x(it) < 0.d0) then
x(it)=x(it)+param%box
endif
if (y(it) > param%box) then
y(it)=y(it)-param%box
else if (y(it) < 0.d0) then
y(it)=y(it)+param%box
endif
if (z(it) > param%box) then
z(it)=z(it)-param%box
else if (z(it) < 0.d0) then
z(it)=z(it)+param%box
endif
call energy(unew,x,y,z,param)
delta = unew-uold
if (delta < 0.) then
potential=potential+delta
ar=1
elseif (exp(-delta/(param%temp)) >= ran()) then
potential=potential+delta
ar=1
else
x(it)=xold
y(it)=yold
z(it)=zold
ar=0
endif
end subroutine move
subroutine energy(u,x,y,z,param)
implicit none
integer :: np,it
type(input),intent(in):: param
double precision :: u
double precision,intent(in) :: x(param%np),y(param%np),z(param%np)
integer :: i,j
double precision :: ddx,ddy,ddz,dd
u=0.0e0
do i=1,param%np-1
do j=i+1,param%np
ddx=x(i)-x(j)
ddy=y(i)-y(j)
ddz=z(i)-z(j)
if (ddx > param%hbox) ddx=ddx-param%box
if (ddy > param%hbox) ddy=ddy-param%box
if (ddz > param%hbox) ddz=ddz-param%box
if (ddx < -param%hbox) ddx=ddx+param%box
if (ddy < -param%hbox) ddy=ddy+param%box
if (ddz < -param%hbox) ddz=ddz+param%box
dd=sqrt(ddx*ddx+ddy*ddy+ddz*ddz)
if (dd <= param%rcut) then
u = u + ( (param%sig/dd)**12 - (param%sig/dd)**6 )
endif
enddo
enddo
u=u*4.0*param%eps
return
end subroutine energy
end module modmove_energy
Finally, the main program is as follows
program lennard
use get_started
use position
use modmove_energy
implicit none
integer :: step,ar
integer :: seed1,seed2
type(input) :: param
double precision, allocatable :: x(:),y(:),z(:)
double precision :: potential
seed1 = 2*int(secnds(0.0))
seed2 = 1+seed1
call srand(seed2)
call init(param)
call print_input(param)
allocate (x(param%np),y(param%np),z(param%np))
call init_position(param,x,y,z,0)
do step=1,param%mceq
call move(potential,param,x,y,z,ar)
! print*,potential
enddo
stop
end program lennard
Sorry for taking your guys time, and thank you for looking at this. The error was in subroutine move, I was assigning x(it) = xold, y(it)=yold,z(it)=zold before having defined xold,yold,zold. rookie mistake!