Hi ,
the following code is working fine but sometimes I got the operation was canceled exception ?
var _options = new ParallelOptions();
_options.MaxDegreeOfParallelism = 5;
Parallel.Invoke(_options,
() =>
{
//get list of item1
foreach (var item in lst_item1)
{
// do some logic here
}
},
() =>
{
//get list of item1
foreach (var item in lst_item2)
{
// do some logic here
}
},
() =>
{
//get list of item1
foreach (var item in lst_item2)
{
// do some logic here
}
});
// continue logic code
Any help would be greatly appreciated!
Regards,
Related
Im setting an Authorize.com charge as per their API reference at https://developer.authorize.net/api/reference/index.html in Node.js.
I can place both ACH and CC transactions just fine, but Im facing a problem with the response from Authorize. Their response takes about 1 second.
After all the parameters such as CC number, expiration date, etc are filled out, I execute a function as follows (ctrl.execute(function () {}):
var ctrl = new ApiControllers.CreateTransactionController(createRequest.getJSON());
ctrl.execute(function () {
var apiResponse = ctrl.getResponse();
var response = new ApiContracts.CreateTransactionResponse(apiResponse);
if (response != null) {
if (response.getMessages().getResultCode() == ApiContracts.MessageTypeEnum.OK) {
if (response.getTransactionResponse().getMessages() != null) {
//transaction approved
AuthorizeResult.status = 1;
}
else {
//transaction rejected
if (response.getTransactionResponse().getErrors() != null) {
AuthorizeResult.status = 0;
}
}
}
else {
if (response.getTransactionResponse() != null && response.getTransactionResponse().getErrors() != null) {
AuthorizeResult.status = 0;
}
else {
AuthorizeResult.status = 0;
}
}
}
else {
AuthorizeResult.status = 0;
}
After I get a result from Authorize, I need to run this code, which Im unable to do, and if I place the code inside the function, I get an error:
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:988:16)
at Module._compile (internal/modules/cjs/loader.js:1036:27)
sqlString = `
insert into AuthorizeBillings (memberid, datetime, authorizeid, messagecode, status, amount, billingtype, errorcode)
values (#memberid, #datetime, #authorizeid, #messagecode, #status, #amount, #billingtype, #errorcode )`
try {
const pool = await utils.poolPromise
const recordset = await pool.request()
.input('memberid', utils.sql.Int, memberid)
.....
.....
.input('errorcode', utils.sql.NVarChar, AuthorizeResult.errorcode)
.query(sqlString)
} catch (err) {
console.log(err)
}
I tried to run this function await but I had no luck. What I need is to continue the code execution AFTER this function returned a value, which I am not able to accomplish properly.
Thanks.
This probably isn't a proper answer... But maybe it will help you out. In order to use await, you have to declare the function as async. So, something like this will allow async workflow:
async function AuthorizeTrans() { // Notice async declaration
var ctrl = new ApiControllers.CreateTransactionController(createRequest.getJSON());
var AuthorizeResult = {
memberid: memberid,
.....
.....
errorcode: ""
}
const res = await ctrl.execute(); // You can now use await
var apiResponse = await res.getResponse();
....... // Rest of code...
SqlExecute(params);
}
async function SqlExecute(params) {
sqlString = `
insert into AuthorizeBillings (memberid, datetime, authorizeid, messagecode, status, amount, billingtype, errorcode)
values (#memberid, #datetime, #authorizeid, #messagecode, #status, #amount, #billingtype, #errorcode )`
try {
const pool = await utils.poolPromise
const recordset = await pool.request()
.input('memberid', utils.sql.Int, memberid)
.....
.....
.input('errorcode', utils.sql.NVarChar, AuthorizeResult.errorcode)
.query(sqlString)
} catch (err) {
console.log(err)
}
}
If you follow the logic from that syntax, you should be on the right track.
How's it going?
I got the example order book code in python (https://support.kraken.com/hc/en-us/articles/360027677512-Example-order-book-code-Python-) and translate it to javascript to run in node. But the book is wrong, it doesn't remove all old prices level. I'm sending my code below. I'd like help to solve this issue.
const websocket = require('ws');
const ws = new websocket('wss://ws.kraken.com');
const api_book = {'bid':[], 'ask':[]};
const api_depth = 10;
const api_output_book = () => {
bid = api_book['bid'].sort((x, y) => parseFloat(y[0])-parseFloat(x[0]));
ask = api_book['ask'].sort((x, y) => parseFloat(x[0])-parseFloat(y[0]));
console.log ('Bid\t\t\t\t\tAsk');
for (let x=0;x<api_depth;x++) {
console.log(`${bid[x][0]} (${bid[x][1]})\t\t\t${ask[x][0]} (${ask[x][1]})`);
}
}
const api_update_book = (side, data) => {
data.forEach((e) => {
let index = api_book[side].findIndex(o => o[0] == e[0]);
if (parseFloat(e[1]) > 0){
if(index < 0){
api_book[side].push([e[0],e[1]]);
} else {
api_book[side][index] = [e[0],e[1]];
}
} else {
api_book[side].splice(index,1);
}
});
if(side=='bid'){
api_book['bid'].sort((x, y) => parseFloat(y[0])-parseFloat(x[0]));
} else if(side=='ask'){
api_book['ask'].sort((x, y) => parseFloat(x[0])-parseFloat(y[0]));
}
}
ws.on('open', open = () => {
ws.send('{"event":"subscribe", "subscription":{"name":"book", "depth":'+api_depth+'}, "pair":["XBT/USD"]}');
console.log('Kraken websocket connected!');
});
ws.on('message', incoming = (data) => {
try {
data = JSON.parse(data.toString('utf8'));
if (data[1]) {
if (data[1]['as']) {
api_update_book('ask', data[1]['as'])
api_update_book('bid', data[1]['bs'])
} else if (data[1]['a'] || data[1]['b']) {
if (data[1]['a']) {
api_update_book('ask', data[1]['a']);
}
if (data[1]['b']) {
api_update_book('bid', data[1]['b']);
}
}
api_output_book();
}
} catch (error) {
console.log(error);
}
});
So I have also been playing around with Kraken's order book and came up with this solution using Angular. I also added a few console logs into the mix so that you can take it and run it in the browser. Hope this helps!
// variables
private ws = new WebSocket('wss://ws.kraken.com')
public asks = [];
public bids = [];
// Web Socket open connection
this.ws.onopen = () => {
this.ws.send(JSON.stringify(this.message));
console.log('Trade WS with Kraken connected')
}
// Fires when new data is received from web socket
this.ws.onmessage = (event) => {
var data = JSON.parse(event.data);
if (!data.event) {
if (data[1]['as']) {
this.asks = data[1]['as'];
this.bids = data[1]['bs'];
console.log('Initialised Book');
console.log(this.asks, this.bids);
} else if (data[1]['a'] || data[1]['b']) {
if (data[1]['a']) {
this.update_book(this.asks, 'ask', data[1]['a']);
}
if (data[1]['b']) {
this.update_book(this.bids, 'bid', data[1]['b']);
}
}
}
}
// Updating Orderbook
update_book (arr, side, data) {
if (data.length > 1) { // If 2 sets of data are received then the first will be deleted and the second will be added
let index = arr.findIndex(o => o[0] == data[0][0]); // Get position of first data
arr.splice(index, 1); // Delete data
arr.push([ data[1][0], data[1][1] ]); // Insert new data
console.log('Delete and Insert');
} else {
let index = arr.findIndex(o => o[0] == data[0][0]);
console.error(index);
if (index > -1) { // If the index matches a price in the list then it is an update message
arr[index] = [data[0][0], data[0][1]]; // Update matching position in the book
console.log('Updated ' + index);
} else { // If the index is -1 then it is a new price that came in
arr.push([data[0][0], data[0][1]]); // Insert new price
this.sort_book(arr, side); // Sort the book with the new price
arr.splice(10, 1); // Delete the 11th entry
console.log('Insert Only');
}
}
this.sort_book(arr, side); // Sort the order book
}
// Sort Orderbook
sort_book (arr, side) {
if (side == 'bid') {
arr.sort((x, y) => parseFloat(y[0]) - parseFloat(x[0]));
} else if (side == 'ask') {
arr.sort((x, y) => parseFloat(x[0]) - parseFloat(y[0]));
}
}
I would also recommend just having a look at this resource:
How to maintain a valid orderbook
I have an API in NestJs which is not sending data on the first hit. However, on hitting it again it sends the desired data. I am guessing the API returns before the internal processing is done.
How to stop this. Is sleep a good option for this?
Or is there any other way to do this?
#Post("load")
#UseGuards(AuthGuard("jwt"))
async load(#Req() body: any)
{
const organizationId = body.user.organizationId;
const userId = body.user.userId;
if ("brandIds" in body.body)
{
await this.userService.onBoardUser(userId);
}
var settings = await this.settingsService.fetchLayout(organizationId, "home");
settings.forEach(async (element) =>
{
var parsedElement = JSON.parse(JSON.stringify(element));
var innerContent = await this.fetchContent(parsedElement.method, organizationId, userId);
var template = parsedElement.content[0];
let formattedItem = {};
innerContent.forEach((item) =>
{
try
{
formattedItem = template;
Object.keys(template).forEach((key) =>
{
if (template[key]!= "" && key != "type")
{
formattedItem[key] = eval(template[key]);
}
});
parsedElement.content.push(formattedItem);
formattedItem = null;
}
catch(err)
{
}
});
this.response.data.push(parsedElement);
innerContent = null;
template = null;
formattedItem = null;
parsedElement = null;
});
return(this.response);
}
looks like your main problem here is that your using async/await inside foreach which isnt working.
Use it like this:
for (const setting of settings) {
... your async code here.
}
How do I get a flattened version of child terms, or just the last level/tier of terms.
Ex: TermSet -->
Term -->
ChildTerm
How do I grab the child term in an SPFX webpart? I can grab the Terms under the termset, but I cant go any deeper.
Tested code based on this thread(test the code to get term of current site).
private getTermsetWithChildren(termStoreName: string, termsetId: string) {
return new Promise((resolve, reject) => {
//const taxonomy = new Session(siteCollectionURL);
const store: any = taxonomy.termStores.getByName(termStoreName);
store.getTermSetById(termsetId).terms.select('Name', 'Id', 'Parent').get()
.then((data: any[]) => {
let result = [];
// build termset levels
do {
for (let index = 0; index < data.length; index++) {
let currTerm = data[index];
if (currTerm.Parent) {
let parentGuid = currTerm.Parent.Id;
insertChildInParent(result, parentGuid, currTerm, index);
index = index - 1;
} else {
data.splice(index, 1);
index = index - 1;
result.push(currTerm);
}
}
} while (data.length !== 0);
// recursive insert term in parent and delete it from start data array with index
function insertChildInParent(searchArray, parentGuid, currTerm, orgIndex) {
searchArray.forEach(parentItem => {
if (parentItem.Id == parentGuid) {
if (parentItem.children) {
parentItem.children.push(currTerm);
} else {
parentItem.children = [];
parentItem.children.push(currTerm);
}
data.splice(orgIndex, 1);
} else if (parentItem.children) {
// recursive is recursive is recursive
insertChildInParent(parentItem.children, parentGuid, currTerm, orgIndex);
}
});
}
resolve(result);
}).catch(fail => {
console.warn(fail);
reject(fail);
});
});
}
Call the function.
this.getTermsetWithChildren(
'Taxonomy_hAIlyuIrZSNizRU+uUbanA==',
'70719569-ae34-4f24-81b9-0629d68c05aa'
).then(data => {
console.log(data);
});
I try to use limit : count with transform observer in Meteor and don't understand how to do it without "dirty" solutions.
Code I have on Client (not all, but main part)
var self = this;
self.autorun(function() {
self.subscribe('posts', Session.get('count')); // some Number like 10
}); // client
And on server where I try to use it
Meteor.publish('posts', function(count){
check(count, Number);
let i = 0;
var transform = function(doc) {
console.log(i,count);
if (i < count){ // I try something here
doc.description = new Date();
i++;
return doc;
}
else self.ready();
}
var self = this;
var observer = Posts.find().observe({
added: function (document) {
self.added('posts', document._id, transform(document));
},
changed: function (newDocument, oldDocument) {
self.changed('posts', document._id, transform(newDocument));
},
removed: function (oldDocument) {
self.removed('posts', oldDocument._id);
}
});
self.onStop(function () {
observer.stop();
});
self.ready();
});
Any idea how to limit count of shown documents with transform in publish ?
Just use Posts.find({},{limit:count}) in your query.