NSLog NSRange problem - sqlite

I have a NSSting resultcontent that contains html data which is dynamic and length of html data is always different according to user input.
I could insert my html data in SQLite3 by replacing " from NSString. Now the problem is that SQlite3 doesn't have any inbuilt function to find the position of a particular substring. In SQL you can use CHARINDEX or Patindex for this purpose.
Now I am trying to find the position of this substring "sphinx". I tried NSrange, substringWithRange etc. but I am not getting the exact start and end positions of this substring. How do you show NSRange in console by using NSLog. Here is my code
//find substring "sphinx"
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"sphinx"
options:NSRegularExpressionCaseInsensitive
error:&error];
//Get total length of resultcontent (NSString which contains whole html code)
NSInteger lengthTotal=[resultContent length];
NSLog(#"lengthTotal is %i", lengthTotal);
// Get NSRange
NSRange rangeOfSubstring = [regex rangeOfFirstMatchInString:resultContent
options:0
range:NSMakeRange(0, lengthTotal)];
NSString *substringData = [resultContent substringWithRange:rangeOfSubstring];
if (!NSEqualRanges(rangeOfSubstring, NSMakeRange(NSNotFound, 0)))
{
NSString *substringData = [resultContent substringWithRange:rangeOfSubstring];
NSLog(#"substringData is %#", substringData);
[b] // so far it works fine and shows substringData ="sphinx" in Console
//But folowing line doesn't show start and end position of substringData "sphinx"
NSLog([#"range of substring is =%#",[resultContent substringWithRange:rangeOfSubstring] ];[/b]
}
How do I find the exact position of a substring from NSString? I also tried %S in NSLog but no results.
I also have the same NSString resultcontent Data in SQLite table (text datatype). How do you find index of a character or position of a substring in Sqlite without Charindex and patindex function. As html code is dynamic and length varies according to the user input so I need to know the index or position of substring after each user input.

Related

Get word at position in Atom

From a linter provider, I receive a Point compatible array(line, column) where the error occured. Now I would like to hightlight the word surrounding that point, basically the result one would get if that exact point was double-clicked in the editor. Something like
const range = textEditor.getWordAtPosition(point)
Is what I hoped for, but couldn't find in the documentation.
Thanks for your help!
After looking around for a while, there seems to be no API method for the given need. I ended up writing a small helper function based upon this answer:
function getWordAtPosition(line, pos) {
// Perform type conversions.
line = String(line);
pos = Number(pos) >>> 0;
// Search for the word's beginning and end.
const left = Math.max.apply(null, [/\((?=[^(]*$)/,/\)(?=[^)]*$)/, /\,(?=[^,]*$)/, /\[(?=[^[]*$)/, /\](?=[^]]*$)/, /\;(?=[^;]*$)/, /\.(?=[^.]*$)/, /\s(?=[^\s]*$)/].map(x => line.slice(0, pos).search(x))) + 1
let right = line.slice(pos).search(/\s|\(|\)|\,|\.|\[|\]|\;/)
// The last word in the string is a special case.
if (right < 0) {
right = line.length - 1
}
// Return the word, using the located bounds to extract it from the string.
return str.slice(left, right + pos)
}
Here, the beginning of the word is determined by the latest occurance of one of the characters (),.[]; or a blank.
The end of the word is determined by the same characters, however here the first occurance is taken as a delimeter.
Given the original context, the function can the be called using the API method ::lineTextForBufferRow and the desired postion (column) as follows:
const range = getWordAtPosition(textEditor.lineTextForBufferRow(bufferRow), 10)

textbox is empty but still showing the count

I have textbox1 field in asp.net and a text area to show count of records.
I want to count the records split by , in textbox1 but when textbox1 is empty text area is showing 1.
Here is the code.
int contacts = textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
String.Split always returns at least one string, if you pass string.Empty you will get one string which is the input string(so in this case string.Empty).
Documentation:
....
If this instance does not contain any of the characters in separator,
the returned array consists of a single element that contains this instance.
You have to check it, f.e. with string.IsNullOrEmpty(or String.IsNullOrWhiteSpace):
int contacts = 0;
if(!string.IsNullOrEmpty(textbox1.Text))
contacts = textbox1.Text.Split(',').Length;
Try this
int contacts = string.IsNullOrEmpty(string.textbox1.Text)? string.empty: textbox1.Text.Split(',').Count();
textarea.Text = contacts.ToString();
This is because even when textbox1.Text is an empty string, that's still treated as one item. You need to use StringSplitOptions.RemoveEmptyEntries so that empty entries are ignored when producing the result of calling Split:
var contacts = textbox1.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Count();
To decompose what you've written into individual statements, what you have is:
var items = textbox1.Text.Split(new char[] { ', ' }, StringSplitOptions.RemoveEmptyEntries);
var countOfItems = itemsFromText.Count();
If you look at items you'll see that it's an array of strings (string[]) which contains one entry for each item in the text from textbox1.Text.
Even if an empty string is passed in (i.e. textbox1 is empty) there's still one string to be returned, hence the fact that your code as written is returning 1, whereas in countOfItems where I've broken the code apart it will have 0 because of the use of StringSplitOptions.RemoveEmptyEntries.
The documentation on msdn of the String.Split overload that takes StringSplitOptions as a parameter has more examples and detail about this.

stringByAddingPercentEscapesUsingEncoding adds unexpected characters?

I'm having a hard time getting my NSURL to work, when I create the final string before converting to URL it adds unwanted character to the end of the string, why is this happening and how can I fix it?
Here is my code:
NSString *remotepathstring = [[NSString alloc] init];
remotepathstring=newdata.remotepath;
NSLog(#"remotepathstring = %#",remotepathstring);
NSString *remotepathstringwithescapes = [remotepathstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"remotepathstring = %#",remotepathstringwithescapes);
remotepathURL =[NSURL URLWithString:remotepathstringwithescapes];
NSLog(#"RemotePathUrl=%#",remotepathURL);
Log outputs as follows:
"remotepathstring = http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf‎"
"remotepathstring = http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf%E2%80%8E"
"RemotePathUrl=http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf%E2%80%8E"
The sequence %E2%80%8E is a Unicode LEFT-TO-RIGHT MARK. This is present in your original remotepathstring, but invisible when printed out via NSLog.
The question becomes: how does newdata.remotepath get populated in the first place? Somewhere along the line it sounds like you need to perform some extra cleanup of input strings to strip out such a character.
Unrelated to the core question, it would seem you're a newcomer to Objective-C. This code is redundant and wasteful:
NSString *remotepathstring = [[NSString alloc] init];
remotepathstring=newdata.remotepath;
You create a string, only to immediately throw it away and replace it with another. If you're not using ARC, this has the additional problem of leaking! Instead do:
NSString *remotepathstring = newdata.remotepath;

how do i delete characters in a string/text of a textbox?

I have an asp.net 4 textbox control that has it's text being dynamically populated by some java script. A Google Maps call to be exact. It's giving me mileage from 1 point to another. When the text displays, it shows " 234 mi" I need to get rid of the "mi" part of this text because the text is being converted to an Int32 Updating a table in my DB.
Basically I can only have an INT. Nothing else in the text box. How do I get rid of the "mi" at the end of the text?
Thanks
C#
EB
On the postback, before you save it you could:
var saveValue = Int32.Parse(tbTarget.Text.Replace("mi", string.Empty).Trim());
If your working with a variable length of chars (say someone enters miles instead) then your must do a foreach against the string (an array of char) and check isnumeric on each char.
A simple String.Substring works also:
String leftPart = TxtMileAge.Text.Substring(0, txt.IndexOf(' '));
int mileAge = int.Parse(leftPart);
This retrieves the part of the String in the range of 0 - indexOfWhiteSpace and converts it to an int
Edit: Since the value can have decimal places (as you've commented), you need to parse it to double, round it and then cast it to int:
var txtEstDistance = new TextBox() { Text = "40.2 mi" };
String leftPart = txtEstDistance.Text.Substring(0, txtEstDistance.Text.IndexOf(' '));
double distanceMiles = double.Parse(leftPart, System.Globalization.CultureInfo.InvariantCulture);
int oDdstanceMiles = (int)Math.Round(distanceMiles, MidpointRounding.AwayFromZero);

iPhone CoreData join

this is my core data model:
I'm trying to get all LanguageEntries from a database for a given category.categoryName and languageset.languageSetName e.g.
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"LanguageEntry" inManagedObjectContext:del.managedObjectContext];
[fetchRequest setEntity:entity];
NSString* predicateString = [NSString stringWithFormat:#"Category.categoryName = %# AND LanguageSet.languageSetName = %#",
#"Food", #"English####Spanish"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString];
NSError *error = nil;
NSArray* objects = [del.managedObjectContext executeFetchRequest:fetchRequest error:&error];
This always returns 0 objects. If I set the predicate string to match on one relationship (e.g. Category.categoryName = Food or languageSet.languageSetName = English####Spanish) it will return data.
This is baffling, can anyone shed some light?
->Ken
Your can't think of Core Data as SQL. There is no such thing as a "join" in Core Data. In this case, your trying to find the intersection of two sets of objects. Close to a join logically but not in the implementation details. And the programming devil is always in the details.
Try using the logical equal "==" like so:
#"Category.categoryName == %# AND LanguageSet.languageSetName == %#"
I believe that will solve your problem.
The data model has a predicate editor hidden way in it. It can help you set up predicates even if you don't embed them in fetches in model itself. Just select an entity, in your case "LanguageEntity", then add a Fetch Request. The edit predicate will appear and you can use the dialog to create the predicate. It will display a textual version of the predicate that you can copy into your code.
The predicate properly wasn't created correctly, you must pass the parameters to predicateWithFormat. It should have been:
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"Category.categoryName = %# AND LanguageSet.languageSetName = %#",
#"Food",
#"English####Spanish"];
In case you were wondering what that does is it puts quotes around the string parameters automatically which are required when using a string in a predicate. When you created the query using NSString's format method that did not put the required quotes in.

Resources