I have a bare bones struct.
struct Transaction {
var value: String = ""
var date: String = ""
var title: String = ""
}
In my project, Transaction is used like so...
var transaction:Transaction = Transaction()
//loops 3 times
repeat {
let parsed = stringAndType(from:myParser)//-> (string:String, type:UInt8)
switch parsed.type {
case 1:
print("1 -- \(parsed.string")
transaction.value = parsed.string
case 2:
print("2 -- \(parsed.string)")
transaction.date = parsed.string
case 4:
print("4 -- \(parsed.string)")
transaction.title = parsed.string
default: break
}
} while myParser.isOk
print("Returning transaction: \(transaction)")
return transaction
In this code, a structure is created. The parser feeds the data to the switch, which assigns the parsed string to the appropriate Transaction variable. When I run the following code, the output indicates that the assignments to transaction.date and transaction.value are not sticking.
Output:
2 -- 12/22/2015
1 -- -5.00
4 -- RECURRING PAYMENT BACKBLAZE
Returning transaction: Transaction(value: "", date: "", title: "RECURRING PAYMENT BACKBLAZE")
There is complex buffering behind the scenes in stringAndType(). Looking at this as a C programmer, I really want to think that function might be the problem. However, I was under the impression that Swift strings are structures, and are therefore copy on write, just like an integer or double. Hoping you can provide insight. Thank you for your time.
Update 02/15/17
The logic in this code is functioning as expected. I think the problem here is memory management. To help drive this point, I've...
Removed the print lines from my switch
Added didSet {} to each variable in Transaction
Like so...
struct Transaction {
var value: String = "" {
didSet {
print("The VALUE has changed from \(oldValue) to \(value)")
}
}
//this is repeated appropriately for the other two variables
}
The given output rules out any logical issues. Output:
The DATE has changed from to 12/22/2015
The VALUE has changed from to -5.00
The TITLE has changed from to RECURRING PAYMENT BACKBLAZE
Returning transaction: Transaction(value: "", date: "", title: "RECURRING PAYMENT BACKBLAZE")
stringAndType() does read from an unsafe buffer, but it copies the bytes to a Data structure, and returns a string initialized from the COPIED data. I thought this would insulate me from safety issues...perhaps theres an implementation detail to String I'm missing?
Credit to #unkgd, you were on the right track with your initial answer before you retracted it. There was a logical error between the while parser.isOk loop and the parent loop (omitted to keep the code short) that was wiping Transaction between value and title being set. There was no indication of this happening in the output. The loop posted above was not looping three times, rather, it was looping once, but that single loop was iterated three times by the parent. Therefore, only the most recent parsed value was stored in the structure, in this case, title. Again, full credit to #unkgd (if you repost your answer and I will mark it as correct). Thanks to everyone for their ideas.
Related
Our VS-2022 development project is Blazor WASM Core-6 with local REST-API for data. Using Postman, my testing is not getting data from the controller call to a repository function -- using breakpoints and local debugging -- as one would expect.
The repository function return statement is return Ok(vehicleTrips);. The IEnumerable vehicleTrips data variable contains the correct four records as expected from the DB fetch.
From the controller the call to the repository function is:
var result = (await motripRepository.GetMOTripsByDateRange((int)eModelType.Vehicle, pVehicleList, pDateFrom, pDateTo)!)!;
The controller function signature is:
[HttpGet("byDateRange/{pVehicleList}/{pDateFrom}/{pDateTo}")]
[ActionName(nameof(GetVehicleMOTripsByDateRange))]
public async Task<ActionResult<IEnumerable<MOTRIP>>> GetVehicleMOTripsByDateRange([FromRoute] string pVehicleList, [FromRoute] string pDateFrom, [FromRoute] string pDateTo) {
This is my problem. The result return value from the repository has a return.Value of null -- NOT four trip records as we should.
Additionally, the VS-Studio's 'local'-debugger shows that there are other properties of return such as .Return and .Return.Value.Count as 4 (four).
My question is "what could be causing this"? All of my other rest-api calls and controller calls with Postman work correctly as one would expect.
Did I select the wrong type of "controller" from Visual-Studio? I am not experienced at all in coding classic MVC web-applications. VS-Blazor offer a number of controller-types. In the past, I "copied" a working controller and "changed the code" for a different "model".
Your assistance is welcome and appreciated. Thanks...John
I found out what actually happened to cause the result.Value is null and had nothing to do with the controller-type -- it was in the interpretation of the return value from the repository function.
I found an SO link Get a Value from ActionResult<object> in a ASP.Net Core API Method that explains how to respond to a ActionResult<objecttype> return value in the reply/answer section with the word "actual" is first defined. You will see this word "actual" in my revised code below.
My revised code is posted here with comments both inside the code section and below the code section. My comment inside the code begins with "<==" with text following until "==>"
// Initialize.
MOTRIP emptyMoTrip = new MOTRIP();
MOTRIP? resultMoTrip = new MOTRIP();
IEnumerable<MOTRIP> allTrips = Enumerable.Empty<MOTRIP>();
int daysPrevious = (int)(pTripType == eTripType.Any ? eDateRangeOffset.Week : eDateRangeOffset.Month);
// convert DateRangeOffset to 'dateonly' values.
DateOnly dtTo = DateOnly.FromDateTime( DateTime.Today);
DateOnly dtFrom = dtTo.AddDays(daysPrevious);
// Fetch the vehicle trips by date-range.
var result = await GetVehicleMOTripsByDateRange(UID_Vehicle.ToString(), dtFrom.ToString(), dtTo.ToString());
if ((result.Result as OkObjectResult) is null) { **<== this is the fix from the SO link.==>**
return StatusCode(204, emptyMoTrip);
}
var statusCode = (result.Result as OkObjectResult)!.StatusCode;
if (statusCode==204) {
return StatusCode(204, emptyMoTrip);
}
**<== this next section allows code to get the result's DATA for further processing.==>**
var actual = (result.Result as OkObjectResult)!.Value as IEnumerable<MOTRIP>;
allTrips = (IEnumerable<MOTRIP>)actual!;
if ((allTrips is not null) && (!allTrips.Any())) {
return StatusCode(204, emptyMoTrip);
}
<== this next section continues with business-logic related to the result-DATA.==>
if (allTrips is not null && allTrips.Any()) {
switch (blah-blah-blah) {
**<== the remainder of business logic is not shown as irrelevant to the "fix".==>**
Please use browser search for "<==" to find my code-comments.
Please use browser search for "actual" and "OkObjectResult" to see the relevant code fix sentences.
Below is the code written by my collegue who doesnt work in the firm anymore. I am inserting records in object with data loader and I can see success message but I do not see any records in my object. I am not able to understand what below trigger is doing.Please someone help me understand as I am new to salesforce.
trigger DataLoggingTrigger on QMBDataLogging__c (after insert) {
Map<string,Schema.RecordTypeInfo> recordTypeInfo = Schema.SObjectType.QMB_Initial_Letter__c.getRecordTypeInfosByName();
List<QMBDataLogging__c> logList = (List<QMBDataLogging__c>)Trigger.new;
List<Sobject> sobjList = (List<Sobject>)Type.forName('List<'+'QMB_Initial_Letter__c'+'>').newInstance();
Map<string, QMBLetteTypeToVfPage__c> QMBLetteTypeToVfPage = QMBLetteTypeToVfPage__c.getAll();
Map<String,QMBLetteTypeToVfPage__c> mapofLetterTypeRec = new Map<String,QMBLetteTypeToVfPage__c>();
set<Id>processdIds = new set<Id>();
for(string key : QMBLetteTypeToVfPage.keyset())
{
if(!mapofLetterTypeRec.containsKey(key)) mapofLetterTypeRec.put(QMBLetteTypeToVfPage.get(Key).Letter_Type__c, QMBLetteTypeToVfPage.get(Key));
}
for(QMBDataLogging__c log : logList)
{
Sobject logRecord = (sobject)log;
Sobject QMBLetterRecord = new QMB_Initial_Letter__c();
if(mapofLetterTypeRec.containskey(log.Field1__c))
{
string recordTypeId = recordTypeInfo.get(mapofLetterTypeRec.get(log.Field1__c).RecordType__c).isAvailable() ? recordTypeInfo.get(mapofLetterTypeRec.get(log.Field1__c).RecordType__c).getRecordTypeId() : recordTypeInfo.get('Master').getRecordTypeId();
string fieldApiNames = mapofLetterTypeRec.containskey(log.Field1__c) ? mapofLetterTypeRec.get(log.Field1__c).FieldAPINames__c : '';
//QMBLetterRecord.put('Letter_Type__c',log.Name);
QMBLetterRecord.put('RecordTypeId',tgh);
processdIds.add(log.Id);
if(string.isNotBlank(fieldApiNames) && fieldApiNames.contains(','))
{
Integer i = 1;
for(string fieldApiName : fieldApiNames.split(','))
{
string logFieldApiName = 'Field'+i+'__c';
fieldApiName = fieldApiName.trim();
system.debug('fieldApiName=='+fieldApiName);
Schema.DisplayType fielddataType = getFieldType('QMB_Initial_Letter__c',fieldApiName);
if(fielddataType == Schema.DisplayType.Date)
{
Date dateValue = Date.parse(string.valueof(logRecord.get(logFieldApiName)));
QMBLetterRecord.put(fieldApiName,dateValue);
}
else if(fielddataType == Schema.DisplayType.DOUBLE)
{
string value = (string)logRecord.get(logFieldApiName);
Double dec = Double.valueOf(value.replace(',',''));
QMBLetterRecord.put(fieldApiName,dec);
}
else if(fielddataType == Schema.DisplayType.CURRENCY)
{
Decimal decimalValue = Decimal.valueOf((string)logRecord.get(logFieldApiName));
QMBLetterRecord.put(fieldApiName,decimalValue);
}
else if(fielddataType == Schema.DisplayType.INTEGER)
{
string value = (string)logRecord.get(logFieldApiName);
Integer integerValue = Integer.valueOf(value.replace(',',''));
QMBLetterRecord.put(fieldApiName,integerValue);
}
else if(fielddataType == Schema.DisplayType.DATETIME)
{
DateTime dateTimeValue = DateTime.valueOf(logRecord.get(logFieldApiName));
QMBLetterRecord.put(fieldApiName,dateTimeValue);
}
else
{
QMBLetterRecord.put(fieldApiName,logRecord.get(logFieldApiName));
}
i++;
}
}
}
sobjList.add(QMBLetterRecord);
}
if(!sobjList.isEmpty())
{
insert sobjList;
if(!processdIds.isEmpty()) DeleteDoAsLoggingRecords.deleteTheProcessRecords(processdIds);
}
Public static Schema.DisplayType getFieldType(string objectName,string fieldName)
{
SObjectType r = ((SObject)(Type.forName('Schema.'+objectName).newInstance())).getSObjectType();
DescribeSObjectResult d = r.getDescribe();
return(d.fields.getMap().get(fieldName).getDescribe().getType());
}
}
You might be looking in the wrong place. Check if there's an unit test written for this thing (there should be one, especially if it's deployed to production), it should help you understand how it's supposed to be used.
You're inserting records of QMBDataLogging__c but then it seems they're immediately deleted in DeleteDoAsLoggingRecords.deleteTheProcessRecords(processdIds). Whether whatever this thing was supposed to do succeeds or not.
This seems to be some poor man's CSV parser or generic "upload anything"... that takes data stored in QMBDataLogging__c and creates QMB_Initial_Letter__c out of it.
QMBLetteTypeToVfPage__c.getAll() suggests you could go to Setup -> Custom Settings, try to find this thing and examine. Maybe it has some values in production but in your sandbox it's empty and that's why essentially nothing works? Or maybe some values that are there are outdated?
There's some comparison if what you upload into Field1__c can be matched to what's in that custom setting. I guess you load some kind of subtype of your QMB_Initial_Letter__c in there. Record Type name and list of fields to read from your log record is also fetched from custom setting based on that match.
Then this thing takes what you pasted, looks at the list of fields in from the custom setting and parses it.
Let's say the custom setting contains something like
Name = XYZ, FieldAPINames__c = 'Name,SomePicklist__c,SomeDate__c,IsActive__c'
This thing will look at first record you inserted, let's say you have the CSV like that
Field1__c,Field2__c,Field3__c,Field4__c
XYZ,Closed,2022-09-15,true
This thing will try to parse and map it so eventually you create record that a "normal" apex code would express as
new QMB_Initial_Letter__c(
Name = 'XYZ',
SomePicklist__c = 'Closed',
SomeDate__c = Date.parse('2022-09-15'),
IsActive__c = true
);
It's pretty fragile, as you probably already know. And because parsing CSV is an art - I expect it to absolutely crash and burn when text with commas in it shows up (some text,"text, with commas in it, should be quoted",more text).
In theory admin can change mapping in setup - but then they'd need to add new field anyway to the loaded file. Overcomplicated. I guess somebody did it to solve issue with Record Type Ids - but there are better ways to achieve that and still have normal CSV file with normal columns and strong type matching, not just chucking everything in as strings.
In theory this lets you have "jagged" csv files (row 1 having 5 fields, row 2 having different record type and 17 fields? no problem)
Your call whether it's salvageable or you'd rather ditch it and try normal loading of QMB_Initial_Letter__c records. (get back to your business people and ask for requirements?) If you do have variable number of columns at source - you'd need to standardise it or group the data so only 1 "type" of records (well, whatever's in that "Field1__c") goes into each file.
First, I'm very new to Swift, and coding in general. I'm trying to use the correct terminology, so I apologize if it makes no sense. Doing my best!
Ok, so there appears to be a lot of information/answers on ways to random select strings (or integers, etc) from an array without repetition. However, in my current application, I am not using an array (I kind of am but not directly related to the question). But rather a #State designation, in which the variable has an initial value (a string with a number and letter) and is later updated when a button is pushed. The string changes to a randomly selected string from my assets folder based on the file name, which will be the same word but with a different number and letter. What is the simplest way to keep from updating to strings that have already appeared?
Example of what the code looks like:
#State var relevantWord = "bird"
Button {
let randoNum = Int.random(in: 1...5)
let x = ["a", "b", "c", "d"]
let randoLet = x.randomElement()
relevantWord = "bird" + String(randoNum) + String(randoLet)
}
So, the relevantWord variable starts as "bird2c" for example, and each time the button is pushed, it will change to "bird3b" then "bird4a" etc. I just want to keep it from repeating and return nothing when the assets are depleted. Thanks!
I'm a swift newbie and I'm working on a Swift Mac App as a demo project.The app stores stock symbols in a sqlite table, fetches the stock price, calculates value and then finally displays the results in a table view.
I'm looking for ways to improve execution speed when fetching data to populate my table view. So I used Dispatch Queue as shown below. The problem is that the
Stock Price and Stock Value columns (calculated in the async closure) are always empty. What am i doing wrong? The function getStocksData returns a NSMutableArray which is the datasource for my table view
func getStocksData() -> NSMutableArray {
sharedInstance.database!.open()
let resultSet: FMResultSet! = sharedInstance.database!.executeQuery("select stock_id,symbol,company,qty from stocks ", withArgumentsIn: [])
let stocksDBRowsArray : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let stockInfo : StockInfo = StockInfo()
stockInfo.StockID = resultSet.string(forColumn: "stock_id")!
stockInfo.Symbol = resultSet.string(forColumn: "symbol")!
stockInfo.StockCompany = resultSet.string(forColumn: "company")!
stockInfo.Qty = resultSet.string(forColumn: "qty")!
//create queue with unique label to fetch stock price
let queue=DispatchQueue(label:stockInfo.Symbol)
queue.async {
//code to fetch stock price goes here
.....
stockInfo.StockPrice=stockPrice
stockInfo.StockValue=stockPrice*stockInfo.Qty
}
stocksDBRowsArray.add(stockInfo)
}
}
sharedInstance.database!.close()
return stocksDBRowsArray
}
What am i doing wrong?
When your getStocksData() method returns, the StockInfo values may, or may not yet be filled with fetched values. StockInfo values eventually get filled, at some undefined point in time, in an undefined application thread.
That's what the provided code snippet does. Of course this is not what you want, but what you want is not very clear either.
The documentation for Swift's Dispatch library is very terse, and won't help you much understand what is happening. I instead suggest that you study the documentation for dispatch_async, which is the C equivalent of the Swift DispatchQueue.async. It is documented with much more details, and you'll read this key sentence:
Calls to this function always return immediately after the block has been submitted and never wait for the block to be invoked.
Generally don't hesitate switching to the Objective-C documentation when the Swift documentation is lacking. Mastering some Swift technologies sometimes requires this little inconvenience. You'll learn a great deal of information there.
I have a meteor app that takes the text of an article and splits it into paragraphs, sentences, words, and characters and then stores that in a json which I then save as a document in a collection. The document I am testing now ends up as 15133 bytes in mongodb.
When I insert the document it takes about 20 or 30 seconds to insert. Then sometimes it starts going through my article creation routine again and inserts another document. Sometimes it ends up inserting 3 or more documents. Sometimes it behaves as it should and only inserts 1 document into the collection.
What should I be looking for that could be causing this behavior?
Here is my code, as requested:
Meteor.methods({
'createArticle': function (text, title) {
var article = {}
article.title = title
article.userID = "sdfgsdfg"
article.text = text
article.paragraphs = []
var paragraphs = splitArticleIntoParagraphs(text)
console.log("paragraphs", paragraphs)
_.each(paragraphs, function (paragraph, p) {
if (paragraph !== "") {
console.log("paragraph", paragraph)
article.paragraphs[p] = {}
article.paragraphs[p].read = false
article.paragraphs[p].text = paragraph
console.log("paragraphs[p]", article.paragraphs[p])
var sentences = splitParagraphIntoSentences(paragraph)
article.paragraphs[p].sentences = []
}
_.each(sentences, function (sentence, s) {
if (sentence !== "") {
article.paragraphs[p].sentences[s] = {}
console.log("sentence", sentence)
article.paragraphs[p].sentences[s].text = sentence
article.paragraphs[p].sentences[s].read = false
console.log("paragraphs[p].sentences[s]", article.paragraphs[p].sentences[s])
var wordsForward = splitSentenceIntoWordsForward(sentence)
console.log("wordsForward", JSON.stringify(wordsForward))
article.paragraphs[p].sentences[s].forward = {}
article.paragraphs[p].sentences[s].forward.words = wordsForward
// var wordsReverse = splitSentenceIntoWordsReverse(sentence)
_.each(wordsForward, function (word, w) {
if (word) {
// console.log("word", JSON.stringify(word))
// article.paragraphs[p].sentences[s] = {}
// article.paragraphs[p].sentences[s].forward = {}
// article.paragraphs[p].sentences[s].forward.words = []
article.paragraphs[p].sentences[s].forward.words[w] = {}
article.paragraphs[p].sentences[s].forward.words[w].wordID = word._id
article.paragraphs[p].sentences[s].forward.words[w].simp = word.simp
article.paragraphs[p].sentences[s].forward.words[w].trad = word.trad
console.log("word.simp", word.simp)
var characters = word.simp.split('')
console.log("characters", characters)
article.paragraphs[p].sentences[s].forward.words[w].characters = []
_.each(characters, function (character, c) {
if (character) {
console.log("character", character, p, s, w, c)
article.paragraphs[p].sentences[s].forward.words[w].characters[c] = {}
article.paragraphs[p].sentences[s].forward.words[w].characters[c].text = character
article.paragraphs[p].sentences[s].forward.words[w].characters[c].wordID = Words.findOne({simp: character})._id
}
})
}
})
}
})
})
// console.log("article", JSON.stringify(article))
// console.log(JSON.stringify(article.paragraphs[10].sentences[1].forward))//.words[4].characters[0])
console.log("done")
var id = Articles.insert(article)
console.log("id", id)
return id
}
})
I call the method here:
Template.articleList.events({
"click #addArticle": function(event) {
event.preventDefault();
var title = $('#title').val();
var text = $('#text').val();
$('#title').value = '';
$('#text').value = '';
$('#text').attr('rows', '3');
Meteor.call('createArticle', text, title);
}
})
An important thing to keep in mind is that meteor methods do not work very well when it comes to perform CPU intensive tasks. Since your meteor server only works in a single thread, any kind of blocking computations - like yours - will affect all client connections, e.g. delaying DDP heartbeats. This - in turn - can result in clients thinking that the connection was dropped.
As #ghybs suggested in one of the comments your method is probably triggered several times by an impatient DDP client who thinks that server has disconnected. The easiest way to prevent this behavior is by adding noRetry flag to Meteor.apply as explained here:
https://docs.meteor.com/api/methods.html#Meteor-apply
I believe Meteor.call does not have this option.
Another strategy would be trying to make sure that your methods are idempotent, i.e. calling them more than once should not produce any additional effects. This is usually true - at least when you use method simulation - because retrying db insert will re-use the same document id which will fail on the second try. For some reason this is not happening in your case.
Finally, the problem you described clearly shows that probably a different pattern should be used for a computationally expensive task like yours. If I were you, I would start by splitting the job in several steps:
First I would make sure that the document is uploaded to the server with a POST request rather than through DDP.
Then I would implement a "process file" server side method that grabs the file which is already on the server or in the database (in case you used files collection). The first thing the method should do would be calling this.unblock(), but thats not all.
Ideally the computational task should be executed in a separated process. Only when that process is completed the method would return telling the actual caller that the job is done. But since we called this.unblock() that caller can perform different tasks, e.g. calling other methods/subscriptions while waiting for the result.
Sometimes, having a separated process will not be good enough. I've experienced situations where I had to delegate the task to another worker server(s).