I was trying to use EnumProcesses with node-ffi. I got code below:
import ffi from 'ffi'
export const psapi = ffi.Library('psapi', {
EnumProcesses: ['bool', ['ulong', 'ulong', 'uint16*']]
})
export class Win32ProcessManager {
public async getProcessList () {
let lpidProcess = ref.alloc('ulong*')
const cb = 1024
const lpcbNeeded = ref.alloc('uint16*')
const res = psapi.EnumProcesses(lpidProcess, cb, lpcbNeeded)
const ulongSize = (ref as any).sizeof.ulong
const totalBytesReturned = lpcbNeeded.readInt16LE()
const processCount = totalBytesReturned / ulongSize
console.log(`processCount: ${processCount}`)
// ??? How to get the value from the lpidProcess?
return lpidProcess
}
}
I tried with ref.get but I encountered errors:
let processId = ref.get(array, 0, ref.types.ulong)
console.log(processId)
const pointerSize = (ref as any).sizeof.pointer
console.log(pointerSize)
let processId2 = ref.get(array, (ref as any).sizeof.pointer, ref.types.ulong)
console.log(processId2)
Errors:
RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to write outside buffer bounds
Anyone knows how to use node-ffi read the array data from dll?
Thanks #DrakeWu-MSFT, I finally got my code works, here are how they looks finally:
import ffi from 'ffi';
import ref from 'ref';
import ArrayType from "ref-array";
export const psapi = ffi.Library('psapi', {
EnumProcesses: ['bool', ['ulong*', 'ulong', 'uint16*']],
});
export class Win32ProcessManager {
public getProcessIdList (): number[] {
const processIdLength = 1024;
const ulongSize = (ref as any).sizeof.ulong;
const cb = processIdLength * ulongSize;
let processIdArray = ArrayType('ulong', processIdLength);
let lpidProcess = ref.alloc(processIdArray);
const lpcbNeeded = ref.alloc('uint16*');
const res = psapi.EnumProcesses(lpidProcess, cb, lpcbNeeded);
if (res) {
const totalBytesReturned = lpcbNeeded.readInt16LE();
const processCount = totalBytesReturned / ulongSize;
const processArray = (lpidProcess as any).deref();
let resultProcessArray: number[] = [];
for (let i = 0; i < processCount; i++) {
resultProcessArray.push(processArray[i]);
}
return resultProcessArray;
} else {
console.error(`Get process list failed with result from EnumProcess: ${res}`);
return [];
}
}
}
I was struggled with getting array data from the pointer, and that was wrong, as #DrakeWu-MSFT said in the comment, because I didn't allocate enough spaces for the buffer, no data can be write into that. With ref-array and a pointer to the array, it works like a charm.
Related
I'm trying to combine a onEdit script with an import range script, I tried using "if" to check if there's a single TRUE checkbox on the selected range but the import range part does not work only the checkbox part.
I need to import only after a single TRUE checkbox is enabled on column 7 otherwise the other spreadsheet glitches.
Source for the checkbox validation script: https://stackoverflow.com/a/71798583/18249133
function onEdit(e) {
const ss = SpreadsheetApp.getActiveSheet()
const { range: { columnStart, rowStart, rowEnd }, value } = e
if (value === "FALSE") return;
const checkRowStart = 4
const checkRowEnd = 200
const checkColumn = 7
if (columnStart === checkColumn && checkRowStart <= rowStart && checkRowEnd >= rowEnd) {
for (let i = 0; i < checkRowEnd; i++) {
ss.getRange(i + checkRowStart, checkColumn).setValue(false)
}
ss.getRange(rowStart, columnStart).setValue(true)
}
}
Import range script
function import(){
importRange(
"SPREADSHEET_ID",
"SHEET NAME + RANGE",
"SPREADSHEET_ID",
"SHEET NAME + RANGE",
);
};
function importRange(sourceID, sourceRange, destinationID, destinationRangeStart) {
const sourceSS = SpreadsheetApp.openById(sourceID);
const sourceRng = sourceSS.getRange(sourceRange);
const sourceVals = sourceRng.getValues();
const destinationSS = SpreadsheetApp.openById(destinationID);
const destStartRange = destinationSS.getRange(destinationRangeStart);
const destSheet = destinationSS.getSheetByName(destStartRange.getSheet().getName());
const destRange = destSheet.getRange(
destStartRange.getRow(),
destStartRange.getColumn(),
sourceVals.length,
sourceVals[0].length
);
destRange.setValues(sourceVals);
};
Thanks in advance :]
I'm using the hive database. My code is:
HiveStocktaking? stocktaking =
_database.getStocktakingById(_stocktakingId);
StocktakingStats stocktakingStats =
_database.getStocktakingStats(_stocktakingId, true);
List<HiveStocktakingItem> stocktakingItemShortage = _database
.getStocktakingAllItem(_stocktakingId, 'shortage', '',
getAll: withProducts)
.values
.first;
List<HiveStocktakingItem> stocktakingItemSurplus = _database
.getStocktakingAllItem(_stocktakingId, 'surplus', '',
getAll: withProducts)
.values
.first;
int shortageLength = withProducts ? stocktakingItemShortage.length : 0;
int surplusLength = withProducts ? stocktakingItemSurplus.length : 0;
if (type == 'excel') {
createIsolate(
stocktaking,
stocktakingStats,
stocktakingItemShortage,
stocktakingItemSurplus,
shortageLength,
surplusLength,
);
}
Future createIsolate(
HiveStocktaking? stocktaking,
StocktakingStats stocktakingStats,
List<HiveStocktakingItem> stocktakingItemShortage,
List<HiveStocktakingItem> stocktakingItemSurplus,
int shortageLength,
int surplusLength) async {
ReceivePort receivePort = ReceivePort();
Isolate.spawn(isolateFunction, receivePort.sendPort);
SendPort childSendPort = await receivePort.first;
ReceivePort responsePort = ReceivePort();
childSendPort.send([
stocktaking,
stocktakingStats,
stocktakingItemShortage,
stocktakingItemSurplus,
shortageLength,
surplusLength,
responsePort.sendPort
]);
var sum = await responsePort.first;
print('sum: $sum');
}
void isolateFunction(SendPort mainSendPort) async {
ReceivePort childReceivePort = ReceivePort();
mainSendPort.send(childReceivePort.sendPort);
await for (var message in childReceivePort) {
HiveStocktaking? stocktaking = message[0];
StocktakingStats stocktakingStats = message[1];
List<HiveStocktakingItem> stocktakingItemShortage = message[2];
List<HiveStocktakingItem> stocktakingItemSurplus = message[3];
int shortageLength = message[4];
int surplusLength = message[5];
SendPort replyPort = message[6];
//heavy task
sync.Workbook workbook = sync.Workbook();
var sheet = workbook.worksheets[0];
sheet.getRangeByIndex(1, 1)
..setText('Отчет по инвентаризации')
..columnWidth = 40
..cellStyle.bold = true
..rowHeight = 30
..cellStyle.fontSize = 20;
sheet.getRangeByIndex(2, 1).setText('Магазин: ${stocktaking?.shopName}');
sheet
.getRangeByIndex(3, 1)
.setText('Дата начала: ${stocktaking?.createdAt}');
sheet
.getRangeByIndex(4, 1)
.setText('Дата завершения: ${stocktaking?.finishedAt}');
sheet.getRangeByIndex(2, 3)
..setText(
'Отсканировано товаров: ${BaseFunctions.numberRound(stocktakingStats.totalScannedMeasurementValue)}')
..columnWidth = 30;
sheet.getRangeByIndex(3, 3).setText(
'Недостач: ${BaseFunctions.numberRound(stocktakingStats.totalMeasurementValue)}');
sheet.getRangeByIndex(4, 3).setText(
'Излишков: ${BaseFunctions.numberRound(stocktakingStats.surplus)}');
// etc generating codes
List<int> bytes = workbook.saveAsStream();
workbook.dispose();
var uint8list = Uint8List.fromList(bytes);
if (Platform.isMacOS) {
String fileName = 'stocktaking_report_' +
DateFormat('dd-MM-yyyy_HH-mm-ss').format(DateTime.now()) +
'.pdf';
String? path =
await PathProviderPlatform.instance.getApplicationSupportPath();
final File file =
File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName');
await file.writeAsBytes(bytes, flush: true);
await Process.run('open', <String>['$path/$fileName'], runInShell: true);
} else {
await FileSaver.instance.saveFile(
'stocktaking_report_' +
DateFormat('dd-MM-yyyy_HH-mm-ss').format(DateTime.now()),
uint8list,
'xlsx',
mimeType: MimeType.MICROSOFTEXCEL,
);
}
replyPort.send(1);
}
}
But it is throwing this error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Invalid argument(s): Illegal argument in isolate message: (object extends NativeWrapper - Library:'dart:io' Class: _RandomAccessFileOpsImpl#13069316)
if I give the createIsolate fake data it works perfectly.
if (type == 'excel') {
ProjectFiles.createIsolate(
HiveStocktaking(),
StocktakingStats(),
[],
[],
0,
0,
);
}
I found a way to solve this issue. If you want to use the hive database in an isolate function note that you must init your database in the isolate function and close the boxes (which you want to use in the isolate) in the main thread. Register the boxes' adapter in the isolate. After your doing close the boxes which opened in isolate. To initiate the database in isolate, you have to set the database path to Hive.init(path). You can send this path through isolate's port. If you want to use closed boxes in the main thread you have to reopen it. Here some codes for example:
static Future<bool> myFunc() async {
ReceivePort receivePort = ReceivePort();
Isolate.spawn(isolateFunc, receivePort.sendPort);
SendPort childSendPort = await receivePort.first;
await Hive.box<YourBox>('boxName').close();
// database path
Directory appDocumentDir = await getApplicationDocumentsDirectory();
ReceivePort responsePort = ReceivePort();
childSendPort.send([appDocumentDir, responsePort.sendPort]);
var sum = await responsePort.first;
var box = await Hive.openBox<YourBox>('boxName');
HiveDatabase.setInstanceYourBox(box);
return sum == 1;
}
static void isolateDownloadStocktaking(SendPort mainSendPort) async {
ReceivePort childReceivePort = ReceivePort();
mainSendPort.send(childReceivePort.sendPort);
await for (var message in childReceivePort) {
Directory appDocumentDir = message[0];
Hive.init(appDocumentDir.path);
Hive.registerAdapter(YourBoxAdapter());
await HiveDatabase.getInstanceYourBox();
// you can use your box
SendPort replyPort = message[1];
await Hive.box<YourBox>('boxName').close();
replyPort.send(1);
}
}
HiveDatabase class is here:
class HiveDatabase {
static Box<YourBox>? _yourBox;
static HiveDatabase instance = HiveDatabase._();
HiveDatabase._();
static Future<HiveDatabase> getInstanceYourBox() async {
_yourBox ??= await Hive.openBox<YourBox>('boxName');
return instance;
}
static Future<HiveDatabase> setInstanceYourBox(Box<YourBox> box) async {
_yourBox = box;
return instance;
}
List<YourBox> elements() {
return (_yourBox?.values ?? []).toList();
}
Future<void> updateElement(YourBox value) async {
await _yourBox?.put(value.id, value);
}
Future<void> addElement(YourBox value) async {
await _yourBox?.put(value.id, value);
}
Future<void> deleteElement(int index) async {
await _yourBox?.deleteAt(index);
}
Future<void> clearYourBox() async {
await _yourBox?.clear();
}
}
I am using veins 5.1. I am trying use getCurrentPosition() function present in TraCIMobility. But it says there is no such function like that? How do I get the current position of a node?
My application source code:
bool VeinsInetSampleApplication::startApplication()
if (getParentModule()->getIndex() == 0) {
auto callback = [this]() {
veins::TraCICommandInterface::Junction traciJunction = traci->junction("node4");
veins::TraCICommandInterface::Junction traciJunction1 = traci->junction("node6");
veins::Coord nodes1 = traciJunction.getPosition();
veins::Coord nodes2 = traciJunction1.getPosition();
veins::Coord veh_pos = mobility_veins->getPositionAt(simTime());
};
timerManager.create(veins::TimerSpecification(callback).interval(SimTime(6, SIMTIME_S)));
}
return true;
And I have defined mobility_veins in the header file as
class VEINS_INET_API VeinsInetApplicationBase : public inet::ApplicationBase, public inet::UdpSocket::ICallback {
protected:
veins::VeinsInetMobility* mobility;
TraCIMobility* mobility_veins;
veins::TraCICommandInterface* traci;
veins::TraCICommandInterface::Vehicle* traciVehicle;
veins::TimerManager timerManager{this};
inet::L3Address destAddress;
const int portNumber = 9001;
inet::UdpSocket socket;
You can get the current position by:
mobility->getPositionAt(simTime());
I'm trying to execute an Pancakeswap swapExactTokensForTokens using ethers.js but i just keep getting the error invalid response - sendTransaction. Unfortunatly the error doesnt contain any more usefull information then that :(
My code:
const provider = new ethers.providers.WebSocketProvider(config.network);
const tradeWallet = ethers.Wallet.fromMnemonic(config.mnemonic);
const account = tradeWallet.connect(provider);
const router = new ethers.Contract(
'0x10ED43C718714eb63d5aA57B78B54704E256024E',
[
'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
'function swapExactTokensForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts)'
],
account
);
[snip]
var amountIn = ethers.utils.parseUnits('0.001', 'ether');
var tokenIn = '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c';
var tokenOut = '0xd2de3fd31b5c9e1557cf329032615a2870a29ccd';
var gasPrice = '5000000000';
var gasLimit = '231795'
var amounts = await router.getAmountsOut(amountIn, [tokenIn, tokenOut])
const amountOutMin = amounts[1].sub(amounts[1].div(10));
// values at the time where:
// tokenIn: 100000000000000 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c (WBNB)
// tokenOut: 1810636794711288351 0xd2de3fd31b5c9e1557cf329032615a2870a29ccd
var tx = router.swapExactTokensForTokens(
amountIn,
amountOutMin,
[tokenIn, tokenOut],
addresses.recipient,
Date.now() + 1000 * 60 * 3, //10 minutes
{ gasPrice: gasPrice,
gasLimit: gasLimit
}
);
const receipt = await tx.wait();
use 'swapExactTokensForETHSupportingFeeOnTransferTokens',Because your 'tokenOut' token has a tax function
I'm trying to use android.media.AudioRecord to save audio, initialization is OK, startRecording() is also called without error, but when I start reading audio from the buffer I got error Failed resolving method read on class android.media.AudioRecord.
Here is the code:
const SAMPLE_RATE = 44100;
const RECORD_AUDIO = android.Manifest.permission.RECORD_AUDIO;
const AudioRecord = android.media.AudioRecord;
const AudioFormat = android.media.AudioFormat;
const MediaRecorder = android.media.MediaRecorder;
ngOnInit(): void {
this.bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
if (this.bufferSize == AudioRecord.ERROR || this.bufferSize == AudioRecord.ERROR_BAD_VALUE) {
this.bufferSize = SAMPLE_RATE * 2;
}
this.bufferSize = this.bufferSize * 10;
this.audioBuffer = new Array(this.bufferSize / 2);
if (!permissions.hasPermission(RECORD_AUDIO)) {
permissions.requestPermission(RECORD_AUDIO).then(() => {
this.createRecorder();
}, (err) => {
console.log('[BrowseComponent] ngOnInit, ', 'permissions error:', err);
});
}
else {
this.createRecorder();
}
}
createRecorder() {
this.record = new AudioRecord.Builder()
.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION)
.setAudioFormat(new AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_PCM_16BIT)
.setSampleRate(SAMPLE_RATE)
.setChannelMask(AudioFormat.CHANNEL_IN_MONO)
.build())
.setBufferSizeInBytes(this.bufferSize)
.build();
this.recordState = this.record && this.record.getState();
if (this.recordState != AudioRecord.STATE_INITIALIZED) {
console.error('[BrowseComponent] createRecorder, ', 'AudioRecord can\'t initialize, state:', this.recordState);
return;
}
console.log('[BrowseComponent] createRecorder, ', 'AudioRecord:', this.record);
}
startRecord() {
this.recording = true;
this.record.startRecording();
this.shortsRead = 0;
while (this.recording) {
const numberOfShort = this.record.read(this.audioBuffer, 0, this.bufferSize);
this.shortsRead += numberOfShort;
// Do something with the audioBuffer
}
}
startRecord() is called from (tap) button handler.
Any ideas what may be wrong?
I guess the problem is that you are passing JavaScript Array instead of the Java Primitive (short) typed Array, so the runtime is unable to identify a method that matches the given parameters.
Use Array.create method to typecast, refer the docs here for more details.