How to support passing non-pointered value .use DLL,VARIANT - dll

E.g:
//BmOpcDaClt_API BOOL _stdcall BMDACReadItem(DWORD ServerHandle,DWORD GroupHandle,DWORD ItemHandle,VARIANT* Value,FILETIME* pTimeStamp,WORD* pQuality)
var Value *ole.VARIANT
Value1 := ole.VARIANT{}
Value = &Value1
var pTimeStamp *w32.FILETIME
pTimeStamp1 := w32.FILETIME{}
pTimeStamp = &pTimeStamp1
var pQuality *uint16
var pQuality1 uint16 = 0
pQuality = &pQuality1
BMDAC_ReadItem.Call(uintptr(ConnectHandle), uintptr(GroupHandle), uintptr(ItemHandle), uintptr(unsafe.Pointer(Value)), uintptr(unsafe.Pointer(pTimeStamp)), uintptr(unsafe.Pointer(pQuality)))
// this is ok!!!
//but
//BmOpcDaClt_API BOOL _stdcall BMDACWriteItem(DWORD ServerHandle,DWORD GroupHandle,DWORD ItemHandle,VARIANT Value, BOOL DoAsync)
BMDAC_WriteItem.Call(uintptr(ConnectHandle), uintptr(GroupHandle), uintptr(ItemHandle), ????, uintptr(0))
//How to do ?

Related

How to connect to the CDP WebSocket server in Golang?

I want to send CDP commands to WebSocket server exposed by chrome browser.
For example, I create a new session on selenium and get WebSocket url as -> ws://172.20.10.2:4444/session/335d5805e9d98f3c37af004fa91e0f6e/se/cdp
Now I want to send CDP commands to this WebSocket connection and get results.
Sample client code :
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net/url"
)
type message1 struct {
Id int `json:"id"`
Result Result `json:"result"`
}
type Result struct {
TargetInfo []TargetInfo `json:"targetInfos"`
}
type TargetInfo struct {
TargetId string `json:"targetId"`
}
type message2 struct {
Id int `json:"id"`
Method string `json:"method"`
Params Parameter `json:"params"`
}
type Parameter struct {
TargetId string `json:"targetId"`
Flatten bool `json:"flatten"`
}
type message3 struct {
Id int `json:"id"`
Method string `json:"method"`
SessionId string `json:"sessionId"`
Parameters EmulationParameter `json:"params"`
}
type EmulationParameter struct {
Width int `json:"width"`
Height int `json:"height"`
DeviceScaleFactor int `json:"deviceScaleFactor"`
Mobile bool `json:"mobile"`
}
type Response2 struct {
Method string `json:"method"`
Parameter SessionResponse `json:"params"`
}
type SessionResponse struct {
SessionId string `json:"sessionId"`
}
type message4 struct {
Id int `json:"id"`
Method string `json:"method"`
SessionId string `json:"sessionId"`
Parameters ScreenshotParameter `json:"params"`
}
type ScreenshotParameter struct {
Width int `json:"width,omitempty"`
}
func main() {
hostURL := "172.20.10.2:4444"
pathURL := "/session/dd44b246de3261c405cb9fcb017ab59a/se/cdp"
u := url.URL{Scheme: "ws", Host: hostURL, Path: pathURL}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
messageChannel := make(chan string)
go func() {
for {
_, message, err := c.ReadMessage()
//err = c.ReadJSON(p)
if err != nil {
log.Println("read:", err)
return
}
messageChannel <- string(message)
fmt.Println(string(message))
}
}()
message := "{\"id\":1,\"method\":\"Target.getTargets\"}"
//err = c.WriteJSON(websocket.TextMessage, []byte(message))
err = c.WriteMessage(websocket.TextMessage, []byte(message))
if err != nil {
log.Println("write:", err)
return
}
response := <-messageChannel
fmt.Println(response)
decodedResponse := message1{}
json.Unmarshal([]byte(response), &decodedResponse)
fmt.Println(decodedResponse)
fmt.Println(decodedResponse.Result.TargetInfo[0].TargetId)
temp := message2{}
temp.Id = 2
temp.Method = "Target.attachToTarget"
temp.Params.Flatten = true
temp.Params.TargetId = decodedResponse.Result.TargetInfo[0].TargetId
event2, _ := json.Marshal(temp)
err = c.WriteMessage(websocket.TextMessage, event2)
if err != nil {
log.Println("write:", err)
return
}
response2 := <-messageChannel
fmt.Println(response2)
decodedResponse2 := Response2{}
json.Unmarshal([]byte(response2), &decodedResponse2)
fmt.Println("The session Id is")
fmt.Println(decodedResponse2.Parameter.SessionId)
width := 645
height := 9651
scale := 2
temp2 := message3{}
temp2.Id = 1
temp2.SessionId = decodedResponse2.Parameter.SessionId
temp2.Method = "Emulation.setDeviceMetricsOverride"
temp2.Parameters.DeviceScaleFactor = scale
temp2.Parameters.Height = height
temp2.Parameters.Width = width
temp2.Parameters.Mobile = false
event3, _ := json.Marshal(temp2)
err = c.WriteMessage(websocket.TextMessage, event3)
if err != nil {
log.Println("write:", err)
return
}
response3 := <-messageChannel
fmt.Println(response3)
temp3 := message4{}
temp3.Id = 1
temp3.SessionId = decodedResponse2.Parameter.SessionId
temp3.Method = "Page.captureScreenshot"
event4, _ := json.Marshal(temp3)
err = c.WriteMessage(websocket.TextMessage, event4)
if err != nil {
log.Println("write:", err)
return
}
response4 := <-messageChannel
fmt.Println(response4)
}
I wasn't able to reuse this part of the code to send CDP commands to the WebSocket. I want a simple example CDP command.

Reference Equality in Kotlin

I'm learning Kotlin, in the tutorial example:
fun main() {
val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a
val b: Int = 1000
val boxedB: Int? = b
val anotherBoxedB: Int? = b
println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // false
}
Why is the result of two comparision different?
Most likely because of the JDK implementation of Integer.valueOf
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(int)
Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
If you decompile the method in Intellij, you'll find
public static final void main() {
int a = 100;
Integer boxedA = Integer.valueOf(a);
Integer anotherBoxedA = Integer.valueOf(a);
int b = 1000;
Integer boxedB = Integer.valueOf(b);
Integer anotherBoxedB = Integer.valueOf(b);
boolean var6 = boxedA == anotherBoxedA;
boolean var7 = false;
System.out.println(var6);
var6 = boxedB == anotherBoxedB;
var7 = false;
System.out.println(var6);
}

I can't figure out how to call a variable from another method

I am am trying to call a variable in another method to my array.
var Com = the difficulty for the game. But the method below I'm trying to call the var Com, for: var c = Com.GetChoice();
Not sure why I can not figure out how to call it.
public object SetDiff()
{
Console.WriteLine("Enter difficulty #: (1 = Easy, 2 = Normal, 3 = Impossible)");
var diff = Console.ReadLine();
int mode;
int.TryParse(diff, out mode);
if (mode == 1)
{
Console.Clear();
var Com = new Easy();
return Com;
}
if (mode == 2)
{
Console.Clear();
var Com = new Medium();
return Com;
}
if (mode == 3)
{
Console.Clear();
var Com = new Hard();
return Com;
}
else
{
Console.WriteLine("That is not a valid input.");
return SetDiff();
}
} // Apparently you can't set variables in a switch.
public int[] FaceOff(int num)
{
int PlayerWin = 0;
int ComWin = 0;
int Tie = num + 1;
// TODO : Get rid of TIES!
for (int i = 0; i < num; i++)
{
var p = p1.GetChoice();
var c = Com.GetChoice();
You have many different options:
Pass as parameter
public int[] FaceOff(int num, int Com){...}
make a "global" variable
private int Com;
I would also recommend you to learn OOP (Object Orientated Programming) basics.

Unstable Postgresql C Function

I'm running PG 9.5 on Win 10 64-bit. I'm compiling C under VS 2016.
I am forming a function that will evolve into a somewhat complex beast. To test out my initial efforts, the function accepts an array of int4 (this works fine and the code for processing it is not shown here). The function then grabs a few rows from a table, pushes the values into a FIFO, then pulls them out and renders the results. This approach is strategic to how the function will operate when complete.
The function works fine on first call, then throws this on any further calls:
ERROR: cache lookup failed for type 0 SQL state: XX000
I have no idea what is causing this.
However, sometimes it doesn't throw an error but executes without end.
Here is my code as lean as I can get it for question purposes:
PG:
CREATE TABLE md_key
(
id serial NOT NULL PRIMARY KEY,
pid int4 NOT NULL,
key integer NOT NULL,
vals int4[]
);
…
CREATE OR REPLACE FUNCTION md_key_query(int4[])
RETURNS TABLE (
id int4,
vals int4[]) AS E'\RoctPG', --abreviated for question
'md_key_query'
LANGUAGE c IMMUTABLE STRICT;
…
select * from md_key_query(array[1,2,3,4]::int4[])
C:
PG_FUNCTION_INFO_V1(md_key_query);
typedef struct
{
Datum id;
Datum vals;
} MdKeyNode;
typedef struct fifoAry
{
MdKeyNode nodes[32];
struct fifoAry *next;
int32 readpos;
int32 writepos;
} FifoAry;
typedef struct
{
FifoAry *fifo;
FifoAry *tail;
FifoAry *head;
uint32 nodescount;
Datum *retvals[2];
bool *retnulls[2];
} CtxArgs;
inline void push(CtxArgs *args, Datum id, Datum vals)
{
if (args->head->writepos == 32)
args->head = args->head->next = (FifoAry*)palloc0(sizeof(FifoAry));
MdKeyNode *node = &(args->head->nodes[args->head->writepos++]);
node->id = id;
node->vals = vals;
args->nodescount++;
}
inline MdKeyNode* pop(CtxArgs *args)
{
// if (!args->nodescount)
// return NULL;
if (args->tail->readpos == 32)
args->tail = args->tail->next;
args->nodescount--;
return &(args->tail->nodes[args->tail->readpos++]);
}
// use STRICT in the caller wrapper to ensure a null isn't passed in
PGMODULEEXPORT Datum md_key_query(PG_FUNCTION_ARGS)
{
uint32 i;
FuncCallContext *funcctx;
HeapTuple tuple;
MdKeyNode *node;
CtxArgs *args;
if (SRF_IS_FIRSTCALL())
{
funcctx = SRF_FIRSTCALL_INIT();
MemoryContext oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
ArrayType *a = PG_GETARG_ARRAYTYPE_P(0);
Datum *in_datums;
bool *in_nulls;
bool fieldNull;
SPITupleTable *tuptable = SPI_tuptable;
int32 ret;
uint32 proc;
if (get_call_result_type(fcinfo, NULL, &funcctx->tuple_desc) != TYPEFUNC_COMPOSITE)
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("function returning record called in context that cannot accept type record")));
deconstruct_array(a, INT4OID, 4, true, 'i', &in_datums, &in_nulls, &ret);
if (!ret)
PG_RETURN_NULL();
(SPI_connect();
// initialize and set the cross-call structure
funcctx->user_fctx = args = (CtxArgs*)palloc0(sizeof(CtxArgs));
args->fifo = args->tail = args->head = (FifoAry*)palloc0(sizeof(FifoAry));
args->retvals = (Datum*)palloc(sizeof(Datum) * 2);
args->retnulls = (bool*)palloc0(sizeof(bool) * 2);
BlessTupleDesc(funcctx->tuple_desc);
// do some work here
// this is simply a test to see if this function is behaving as expected
ret = SPI_execute("select id, vals from public.md_key where vals is not null limit 64", true, 0);
if (ret <= 0)
ereport(ERROR, (errcode(ERRCODE_SQL_ROUTINE_EXCEPTION), errmsg("could not execute SQL")));
proc = SPI_processed;
if (proc > 0)
{
TupleDesc tupdesc = SPI_tuptable->tupdesc;
SPITupleTable *tuptable = SPI_tuptable;
for (i = 0; i < proc; i++)
{
tuple = tuptable->vals[i];
push(args, SPI_getbinval(tuple, tupdesc, 1, &fieldNull), SPI_getbinval(tuple, tupdesc, 2, &fieldNull));
}
}
SPI_finish();
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
args = funcctx->user_fctx;
if (args->nodescount > 0)
{
node = pop(args);
args->retvals[0] = node->id;
args->retvals[1] = node->vals;
tuple = heap_form_tuple(funcctx->tuple_desc, args->retvals, args->retnulls);
SRF_RETURN_NEXT(funcctx, HeapTupleGetDatum(tuple));
}
else
{
SRF_RETURN_DONE(funcctx);
}
}
Fixed it. Moved one command as shown here:
{
// function is unstable if this is put earlier
SPI_finish();
SRF_RETURN_DONE(funcctx);
}

Using variable names as property names in lodash _.findIndex

var ids = ["John", "Mary", "Joe", "Chase", "Sarah"];
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var max = 25; // fixed for simplicity
var maxObj = _.findIndex(people['scores'], { id : max });
}
The above does not work as _.findIndex returns -1 for maxObj. However, if i explicitly define the property name as a string (instead of using the id variable), it works.
var maxObj = _.findIndex(people['scores'], { "John" : max });
Is there a way to pass variable values to the property name in lodash or an alternate way to achieve this using lodash?
You could construct an object literal using the dynamic key and then feed that to _.findIndex:
var ids = ["John", "Mary", "Joe", "Chase", "Sarah"];
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var max = 25; // fixed for simplicity
var obj = {};
obj[id] = max;
var maxObj = _.findIndex(people['scores'], obj);
}