I am using this Code snippet to search for an String inside another String.
It works fine for the first if, but then after the second if it only returns YES (true) if I search for both Words (Word from first if, the Word I want to search now)
works if hypothesis contains : "OPEN TWITTER" not if it is "PLEASE OPEN TWITTER" p.e.
if ([hypothesis rangeOfString:#"OPEN"].location == !NSNotFound) {
NSLog(#"hypothesis contains OPEN");
if ([hypothesis rangeOfString:#"OPEN TWITTER"].location == !NSNotFound) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:#"twitter://"]];
}
if ([hypothesis rangeOfString:#"OPEN FACEBOOK"].location == !NSNotFound) {
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:#"fb://"]];
}
}
I want it to work also if there are any other Words in the String, I just want to it to hit on the Keywords somewhere in the String and then return YES (to determine that 'hypothesis' contains the words and then do the action)
== !NSNotFound
should be changed to
!= NSNotFound
Related
I hope this haven't been asked before I'm trying to do what the title says.
In this particular example I got email list on column A, and I want that email address to receive a notification when the cell next to it gets updates to "Yes"
So far I got this:
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("sendNotification")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onEdit()
.create();
};
/**
*
*/
function sendNotification(e) {
if("B2" == e.range.getA1Notation() ) {
if(e.value == "Yes") {
var recipients = "IDK what to put in here";
var subject = "There's an update to your request";
var body = "We resolved your issue!";
MailApp.sendEmail(recipients, subject, body);
}
}
}
I have edited the code with comments to explain what I changed, you were on the right track. OnEditTriggers to send Email is usually frowned upon, generally not a good practice. However, in your case you still have control on when to send an email, so improvement over just flat out emailing on every Edit.
FYI you dont need Initialize() to setup the manual triggers you can set it up manually: https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_manually
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
// The below code would delete all the triggers in your project not just the one you setup through this code.
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
ScriptApp.newTrigger("sendNotification")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onEdit()
.create();
};
function sendNotification(e) {
//if("B2" == e.range.getA1Notation() ) {
//This will only check is the range is B2 cell, if you want to check for column B. use getColumn
if(e.range.getColumn() == 2){
if(e.value == "Yes") {
//var recipients = "xxx#gmail.com"; //Email Address of the indented Recipents
// In your case email would be the value in cell A2 or cell in Column A corresponding to the one edited in Col B
// you can get that value like so
var recipients = e.source.getActiveSheet().getRange(e.range.getRow(),1).getValue()
Logger.log(recipients)
var subject = "There's an update to your request";
var body = "We resolved your issue!";
MailApp.sendEmail(recipients, subject, body);
}
}
}
New functions:
e.range.getColumn()/getRow() to get the specific column or row. So that way you working with numbers and not string. Easy to manipulate numbers with arithmetic compared to strings.
e.source.getActiveSheet() gives you sheet object of where the change happened. You use e.source.getActiveSheet().getName() to get the name of the sheet and use it to make sure email is only fired when an edit happens on a specific sheet.
I'm working on image mining project, and I used Hashset instead of array to avoid adding duplicate urls while gathering urls, I reached to the point of code to iterate the Hashset that contains the main urls and within the iteration I go and download the the page of the main URL and add them to the Hashet, and go on , and during iteration I should exclude every scanned url, and also exclude ( remove ) every url that end with jpg, this until the Hashet of url count reaches 0, the question is that I faced endless looping in this iteration , where I may get url ( lets call it X )
1- I scan the page of url X
2- get all urls of page X ( by applying filters )
3- Add urls to the Hashset using unioinwith
4- remove the scanned url X
the problem comes here when one of the URLs Y, when scanned bring X again
shall I use Dictionary and the key as "scanned" ?? I will try and post the result here, sorry it comes to my mind after I posted the question...
I managed to solve it for one url, but it seems it happens with other urls to generate loop, so how to handle the Hashset to avoid duplicate even after removing the links,,, I hope that my point is clear.
while (URL_Can.Count != 0)
{
tempURL = URL_Can.First();
if (tempURL.EndsWith("jpg"))
{
URL_CanToSave.Add(tempURL);
URL_Can.Remove(tempURL);
}
else
{
if (ExtractUrlsfromLink(client, tempURL, filterlink1).Contains(toAvoidLoopinLinks))
{
URL_Can.Remove(tempURL);
URL_Can.Remove(toAvoidLoopinLinks);
}
else
{
URL_Can.UnionWith(ExtractUrlsfromLink(client, tempURL, filterlink1));
URL_Can.UnionWith(ExtractUrlsfromLink(client, tempURL, filterlink2));
URL_Can.Remove(tempURL);
richTextBox2.PerformSafely(() => richTextBox2.AppendText(tempURL + "\n"));
}
}
toAvoidLoopinLinks = tempURL;
}
Thanks for All, I managed to solve this issue using Dictionary instead of Hashset, and use the Key to hold the URL , and the value to hold int , to be 1 if the urls is scanned , or 0 if the url still not processed, below is my code.
I used another Dictionary "URL_CANtoSave to hold the url that ends with jpg "my target"...and this loop of While..can loop until all the url of the website ran out based on the values you specify in the filter string variable that you parse the urls accordingly.
so to break the loop you can specify amount of images url to get in the URL_CantoSave.
return Task.Factory.StartNew(() =>
{
try
{
string tempURL;
int i = 0;
// I used to set the value of Dictionary Key, 1 or 0 ( 1 means scanned,
0 means not yet and to iterate until all the Dictionry Keys are scanned or you break in the middle based on how much images urls you collected in the other Dictionary
while (URL_Can.Values.Where(value => value.Equals(0)).Any())
{
// take 1 key and put it in temp variable
tempURL = URL_Can.ElementAt(i).Key;
// check if it ends with your target file extension. in this case image file
if (tempURL.EndsWith("jpg"))
{
URL_CanToSave.Add(tempURL,0);
URL_Can.Remove(tempURL);
}
// if not image go and download the page based on the url and keep analyzing
else
{
// if the url not scanned before then
if (URL_Can[tempURL] != 1)
{
// here it seems complex little bit, where Add2Dic is process to add to Dictionaries without adding the Key again ( solving main problem !! )
"ExtractURLfromLink" is another process that return dictionary with all links analyzed by downloading the document string of the url and analyzing it ,
you can add remove filter string based on you analysis
Add2Dic(ExtractUrlsfromLink(client, tempURL, filterlink1), URL_Can, false);
Add2Dic(ExtractUrlsfromLink(client, tempURL, filterlink2), URL_Can, false);
URL_Can[tempURL] = 1; // to set it as scanned link
richTextBox2.PerformSafely(() => richTextBox2.AppendText(tempURL + "\n"));
}
}
statusStrip1.PerformSafely(() => toolStripProgressBar1.PerformStep());
// here comes the other trick to keep this iteration keeps going until it scans all gathered links
i++; if (i >= URL_Can.Count) { i = 0; }
if (URL_CanToSave.Count >= 150) { break; }
}
richTextBox2.PerformSafely(() => richTextBox2.Clear());
textBox1.PerformSafely(() => textBox1.Text = URL_Can.Count.ToString());
return ProcessCompleted = true;
}
catch (Exception aih)
{
MessageBox.Show(aih.Message);
return ProcessCompleted = false;
throw;
}
{
richTextBox2.PerformSafely(()=>richTextBox2.AppendText(url+"\n"));
}
})
I am currently using the PFUser method ' signUpInBackgroundWithBlock: ' to sign up my users, but constraints on my UX mean that i can't sign them up on the same ViewController, hence I'm trying to validate the email before calling that method on a PFUser Parse object.
The alternative is to send my users back to earlier view controllers if parse gives me an error back after method call (which I do not want to do)
I have found this Regex pattern, but this is quite an old answer and I know fancier domains have been out since are now out:
https://www.parse.com/questions/email-validation-rules-for-pfsignupviewcontroller
"The alternative is to send my users back to earlier view controllers if parse gives me an error back after method call (which I do not want to do)"
Note - Unfortunately, you simply won't be able to build parse apps unless you "send them back" like that. Unfortunately "it's that simple." Quite literally every single such "step" when dealing with Parse, you have to be able to "go back" in the sense you describe.
In answer to your question, as you probably know essentially THERE IS NO really good way to truly check if a string is an email, due to various problems with the nature of defining an email, and the fact that you simply don't actually want the full set of "really possible" email strings, for any app.
In practice the following category works well.
It's in use in many high volume production apps.
Note that NSPredicate is, I feel, the most natural, reliable way to do this in iOS.
-(BOOL)basicLocalEmailCheck
{
if ( self.length > 50 ) return NO;
// note, first if it ends with a dot and one letter - that is no good
// (the regex below from W3C does allow a final single-letter tld)
NSString *rx = #".*\\..$";
NSPredicate *emailTest = [NSPredicate
predicateWithFormat:#"SELF MATCHES %#", rx];
if ( [emailTest evaluateWithObject:self] ) return NO;
// here's the original from the W3C HTML5 spec....
// ^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$
// i made a modification,
// you can't have eg "localhost" with no .com,
// and note you have to escape one backslash for the string from the W3C
rx = #"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?){1,5}$";
emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", rx];
return [emailTest evaluateWithObject:self];
}
If you are a beginner and not familiar with categories, it's a good opportunity to use one.
Here are some typical real-world uses...particularly relating to Parse since you mention that.
-(IBAction)joinNow
{
[self.view endEditing:YES];
if ( [self _fieldBlank] )
{ [self woe:#"Please complete all fields."]; return; }
if ( ! [self.email.text basicLocalEmailCheck] )
{ [self woe:#"Please enter a valid email."]; return; }
if ( self.imageHasBeenSet == NO )
{ [self woe:#"Please add a picture."]; return; }
if ( self.password.text.length > 20 ||
self.firstname.text.length > 20 ||
self.surname.text.length > 20 )
{ [self woe:#"20 character limit for names and password."]; return; }
[self ageConfirmThenJoin];
}
-(IBAction)clickLogin:(id)sender
{
[self.view endEditing:YES];
[PFUser logOut];
if ( ! [self.loginEmail.text basicLocalEmailCheck] )
{
[UIAlertView ok:#"Please enter your email in the email field."];
[self begin];
return;
}
[APP huddie];
APP.hud.labelText = #"Logging in ...";
[PFAnalytics trackEvent:#"loginAttempt"];
[PFUser logInWithUsernameInBackground: [self.loginEmail.text lowercaseString]
password: self.loginPassword.text
block:^(PFUser* user, NSError* error)
{
[APP.hud hide:YES];
if (user) // Login successful
{
[PFAnalytics trackEvent:#"loginSuccess"];
[self isLoggedInCheckValid];
return;
}
else
{
// note, with Parse it SEEMS TO BE THE CASE that
// 100, no connection 101, bad user/pass
NSString *msg;
NSString *analyticsMsg = #"otherProblem";
if ( !error)
{
msg = #"Could not connect. Try again later...";
// seems unlikely/impossible this could happen
}
else
{
if ( [error code] == 101 )
{
msg = #"Incorrect email or password. Please try again.";
analyticsMsg = #"passwordWrong";
}
else
{
msg = #"Could not connect. Try again later.";
}
}
[PFAnalytics trackEvent:#"loginFailure"
dimensions:#{ #"reason":analyticsMsg }];
[UIAlertView ok:msg];
[self begin]; // not much else we can do
return;
}
}];
}
If you are after a regular expression, then you could take a look here and here for some solutions.
That being said, if you truly want to ensure that the user has provided you with a valid, active email account you should simply do some very basic validation (see it contains the # character for instance) and then simply send a mail with a link to activate the account.
The regular expressions linked to the answers provided aren't exactly user friendly. To add insult to injury, users can still provide you with bogus email addresses. It might also be the case where an edge case scenario email address fails the verification, thus according to your site the user won't be able to sign up.
The xpages contain SAVE button. The xpages also contain InternetAddres field.
When user click SAVE button, need to check first on names.nsf
- Save success if InternetAddress value NOT found in names.nsf view "($Users)"
- Save fail if InternetAddress value found in names.nsf view "($Users)"
How to write the script to do that?
This is the LotusScript version of script:
Set namesview = namesdb.GetView( "($Users)" )
Set namesdoc = namesview.GetDocumentByKey( Lcase(doc.CurrentInternetAddress( 0 ) ), True )
If ( namesdoc Is Nothing ) Then '-- Create New Doc
How to move on xpages?
The latest release of the OpenNTF Domino API adds a checkUnique() method to the View class. It takes two parameters, the first being a key to check against the view (e.g. a String or List of Strings), the second being the current document. After all, if you're checking for a pre-existing document, you don't want to fail just because it finds this document in the view.
So assuming CurrentInternetAddress is a single value field, the code would be:
function continueWithValidUser(namesDB, doc) {
var success = false;
try {
var view = namesDB.getView("($Users)");
success = view.checkUnique(doc.getItemValue("CurrentInternetAddress"),doc);
} catch (e) {
print(e.message);
}
return success;
}
OpenNTF Domino API recycles all handles to Domino objects, so the recycle() calls aren't needed.
In your datasource is a querySave event. You write JS there. It is almost the same code. Just with { } and ;
Remarks:
your app will break when there is more than one address book, so you you would want to use #NameLookup which is quite fast and checks all addressbooks.
unless you need the document getEntry is faster than getDocument
In SSJS your function would look like this:
function continueWithValidUser(namesDB, addressCandidate) {
var success = false;
try {
var view = namesDB.getView("($Users)");
var doc = view.getDocumentByKey(addressCandidate);
success = (doc != null);
doc.recycle();
view.recycle();
} catch (e) {
print(e.message);
}
return success;
}
That should do the trick
Is there some function in TweetSharp that could be used in a similar way to my 'IsFollowingMe' below?
I'd like to check whether a user is following me before I attempt to send some private message.
TweetSharp.TwitterService service;
string screenName = "#some_one";
string someMessage = "Some Message";
if (service.IsFollowingMe(screenName))
{
service.SendDirectMessage(screenName, someMessage);
else
NotifyThatSendingNotPossible();
}
First option to such approach is to use:
TweetSharp.TwitterService service;
TwitterCursorList<TwitterUser> followers = service.ListFollowers();
and then iterate through the result to find out if user is following my account. But this will eventually be ineffective when there are a lot of followers.
Another option is to execute service.SendDirectMessage and then check if the result is null or not. I tested such approach with success - however my application logic prefers to check in advance if sending is possible and based on this information should do different actions.
The answer is as follows:
TweetSharp.TwitterService service;
string fromUser = "#mr_sender";
string toUser = "#some_one";
string someMessage = "Some Message";
TweetSharp.TwitterFriendship friendship =
service.GetFriendshipInfo(fromUser, toUser);
if (friendship.Relationship.Source.CanDirectMessage.HasValue &&
friendship.Relationship.Source.CanDirectMessage.Value)
{
service.SendDirectMessage(screenName, someMessage);
}
else
{
NotifyThatSendingNotPossible();
}
I could able to solve this using below way.
var twitterFriendship = service.GetFriendshipInfo(new GetFriendshipInfoOptions() { SourceScreenName = "source_name", TargetScreenName = "target_name"});
After that, you can check like below
if(twitterFriendship.Relationship.Source.Following && twitterFriendship.Relationship.Target.FollowedBy)
{
service.SendDirectMessage(new SendDirectMessageOptions() { ScreenName="target_name",Text="message"})
}