How to get Google search results' snippet using ajax API? - ajax

I'm using one example code from StackOverflow to get the search results' title, URL and snippet:
for (int s = 0; s < 20; s = s + 4)
{
String address = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=" + s + "&q=";
String query = "ucd";
String charset = "UTF-8";
URL url = new URL(address + URLEncoder.encode(query, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
GoogleSearch results = new Gson().fromJson(reader, GoogleSearch.class);
for (int i = 0; i < 4; i++)
{
System.out.println("Title: " + results.getResponseData().getResults().get(i).getTitle().replaceAll("<b>", "").replaceAll("</b>", ""));
System.out.println("URL: " + results.getResponseData().getResults().get(i).getUrl());
System.out.println("Snippet: " + results.getResponseData().getResults().get(i).getSnippet() + "\n");
System.out.println(results.getResponseData().getResults().get(i));
}
}
But it seems that the http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q= does not return the snippet from search.
Any other ways using Google API to get this? Can't find one after search...

Use the method getContent() rather than getSnippet(). For example:
System.out.println("Snippet: " + results.getResponseData().getResults().get(i).getContent() + "\n");

Related

Email body returns a blank or null in chilkat mail

I have the following code that reads a bunch of emails from a folder. It gets the emails fine, as I can see the number of emails are correct and the header is correct as well.
However it returns nothing for the body. I do have a email with simple text as well but that too does not return anything. Part of the code is below.
any help is appreciated. the account I am reading is from a office 365 and i used the imap.Connect
(*i can read these emails from the Microsoft Outlook, so i think the issue is with my chilkat code)
Chilkat.MessageSet messageSet = imap.Search(#"ALL", fetchUids);
if (imap.LastMethodSuccess == false)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + imap.LastErrorText;
return;
}
// Fetch the email headers into a bundle object:
Chilkat.EmailBundle bundle = imap.FetchHeaders(messageSet);
if (imap.LastMethodSuccess == false)
{
txtOutput.Text = txtOutput.Text + Environment.NewLine + imap.LastErrorText;
return;
}
// Sort the email bundle by date, recipient, sender, or subject:
bool ascending = true ; bool descending = true;
bundle.SortByDate(ascending);
//bundle.SortByDate(descending);
// To sort by recipient, sender, or subject, call
// SortBySender, SortByRecipient, or SortBySubject.
// Display the Subject and From of each email.
int i = 0;
string body="";
while (i < bundle.MessageCount)
{
Chilkat.Email email = null;
email = bundle.GetEmail(i);
txtOutput.Text = txtOutput.Text + Environment.NewLine + Environment.NewLine + email.GetHeaderField("Date");
//Debug.WriteLine(email.GetHeaderField("Date"));
//Debug.WriteLine(email.Subject);
txtOutput.Text = txtOutput.Text + Environment.NewLine + email.From;
//Debug.WriteLine(email.From);
//Debug.WriteLine("--");
if (email.HasHtmlBody())
{
body = email.GetHtmlBody() + String.Empty;
}
else if (email.HasPlainTextBody())
{
body = email.GetPlainTextBody() + String.Empty;
}
else
{
body = email.Body + String.Empty;
}
txtOutput.Text = txtOutput.Text + Environment.NewLine + body.Trim() ;
i = i + 1;
}
You downloaded headers-only:
Chilkat.EmailBundle bundle = imap.FetchHeaders(messageSet);
Of course there is no body...

Xamarin UILabel not updating

I've a basic for loop that's basically download files. It's supposed to update the label as long as it progress.
By searching here at Stack Overflow, I found an orientation to use SetNeedsDisplay(). But it's still refuses to update. Any idea ?
for (int i = 0; i < files.Length; i++)
{
status.Text = "Downloading file " + (i + 1) + " of " + files.Length + "...";
status.SetNeedsDisplay();
string remoteFile = assetServer + files[i];
var webClient2 = new WebClient();
string localFile = files[i];
string localPath3 = Path.Combine(documentsPath, localFile);
webClient2.DownloadFile(remoteFile, localPath3);
}
As previously suggested try to avoid blocking the UI when doing heavy transactions in it. WebClient already has a async method which you can use.
webClient2.DownloadFileasync(new System.Uri(remoteFile), localPath3);
and to prevent you from accessing the UI from a different thread use the built-in method InvokeOnMainThread when accessing UI elements.
InvokeOnMainThread (() => {
status.Text = "Downloading file " + (i + 1) + " of " + files.Length + "...";
status.SetNeedsDisplay ();
});
and finally use the using statement to help you with the resources disposal.
using (var webClient2 = new WebClient ())
{
webClient2.DownloadFileAsync (new System.Uri (remoteFile), localPath3);
}
You could also have the iteration inside the using statement this way you don't have to create a WebClient object for each file instead you will use the same object to download all files available in your files array.

is my if statement doing what i think its doing?

Here I have tis function that is querying data and returning it to me and im putting that data in to html elements to make a post.my if statement at the bottom is where im having a bit of problem i trying to only apply my comment window once to the new clones once they have been pushed over to the new div called story board, i believe im telling my if statement that if the class already exists in that new clone then do nothing else apply it there.. to seee what i am talking about...here is my test domain...http://subdomain.jason-c.com/
sign in is "kio" pass is the same and when you hit publish on the stories, everytime a nw one hits it will apply comment box to a post in the storyboard window that already has a comment text area. what am i doing wrong.
function publishWindowHandler(){
var query = new Parse.Query('Post');
console.log(currentUser);
query.equalTo("User", currentUser);
query.include("User");
query.descending("createdAt")
console.log(user.get('username'));
query.find({
success:function(results){
document.getElementById("publishCenter").textContent = "";
for(var i =0; i < results.length; i++){
var userPost = results[i];
//console.log(userPost.get("User") + " / " + userPost.get("Author") + " / " + userPost.get("Story") + " / " + userPost.get("objectId"));
var authorTitle = document.createElement("p");
var newPost = document.createElement("P");
var title = document.createElement("P");
var userLabel = document.createElement("p");
var postId = userPost.id;
var postBtn = document.createElement("INPUT");
postBtn.className ="publishBtn";
postBtn.id ="publishBtn";
postBtn.setAttribute("Type", "button");
postBtn.setAttribute("value", "Publish");
title.textContent = "Story: " + userPost.get("Title");
authorTitle.textContent = "Author: " + userPost.get("Author");
newPost.textContent = userPost.get("Story");
userLabel.textContent = "Published by: " +userPost.get("User").get ("username");
var postWrapper = document.createElement("DIV");
postWrapper.className = "postWrapper";
postWrapper.id = postId;
document.getElementById("publishCenter").appendChild(postWrapper);
postWrapper.appendChild(title);
postWrapper.appendChild(authorTitle);
postWrapper.appendChild(newPost);
postWrapper.appendChild(userLabel);
postWrapper.appendChild(postBtn);
postBtn.addEventListener("click", publicViewHandler);
function publicViewHandler(){
$(this).parent(".postWrapper").clone().appendTo(".storyBoard");
function testWindow(){
if($(publicBoard).children().hasClass(".commentWindow")){
}
else
{
$(".storyBoard").children().append(commentWindow);
}
}
testWindow();
}
}
}
})
}
According to the documentation, jquery hasClass doesn't need '.' prefixing the passed in class name.
https://api.jquery.com/hasclass/
Try removing that and see if that get's you anywhere.
Also, where is the variable commentWindow defined? Is it global?
var myClone = $(this).parent().clone(true);
myClone.appendTo(".storyBoard");
console.log(publicBoard);
console.log("hello",$(this));
console.log($(publicBoard).find('.postWrapper').find("commentWindow"));
myClone.append($(commentWindow).clone());
this is what i ended up doing to solve my issue took me a while and a little help from a friend.

Ace editor - It doesn´t change the error window dynamically

I have the next code:
var exeWindow = document.getElementById("exeWindow");
var errorWindow = document.getElementById("errorWindow");
var annot = editor.getSession().getAnnotations();
editor.getSession().on("changeAnnotation", execute);
function execute(){
exeWindow.innerHTML = eval(editor.getValue());
errorWindow.innerHTML = "";
annot = editor.getSession().getAnnotations();
for (var key in annot){
if (annot.hasOwnProperty(key))
console.log(annot[key].text + "on line " + " " + (parseInt(annot[key].row)+1));
errorWindow.innerHTML = annot[key].text + " Line " + " " + (parseInt(annot[key].row)+1);
exeWindow.innerHTML = "";
}
if (TogetherJS.running) {
TogetherJS.send({type: "execute"});
}
};
Im trying to capture the error logs, and before execute a valid code works, but once I introduce for example 2+2, despite of exeWindow changes correctly, if a rewrite it to 2+a for example, searching a new error, the exeWindow doesn´t changes and the error does not appears in errorWindow.
EDIT: Sorry, the problem is that is not getting the correct errors, only the errors like 'missing semicolon'.
If someone is interested, the solution I found is the next one:
function execute(){
try {
exeWindow.innerHTML = eval(editor.getValue());
errorWindow.innerHTML = "";
} catch(err){
var annot = editor.getSession().getAnnotations();
for (var key in annot){
if (annot.hasOwnProperty(key)){
errorWindow.innerHTML = annot[key].text + " Line " + " " + (parseInt(annot[key].row)+1);
exeWindow.innerHTML = "";
}
}
}
if (TogetherJS.running) {
TogetherJS.send({type: "execute"});
}
};
Simple as that :)

How to replace a String at the end when Building a String with multiple Data?

HI all i am Building A string Which looks like this
[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
i am building this string with this data
public JsonResult ResourceBugReports()
{
int projectid;
int Releasphaseid;
projectid = 16;
Releasphaseid = 1;
var ResourceReports = db.ExecuteStoreQuery<ResourceModel>("ResourceBugReports #ProjectId,#ReleasePhaseId", new SqlParameter("#ProjectId", projectid), new SqlParameter("#ReleasePhaseId", Releasphaseid)).ToList();
DataSet ds = new DataSet();
var model1 = new WeeklyBugCount
{
Resources = ResourceReports
};
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
foreach (var row in model1.Resources)
{
BugsCount = BugsCount + row.Assignedbugs + ",";
}
foreach (var row in model1.Resources)
{
BugsCount1 = BugsCount1+ row.Closedbugs + ",";
}
foreach (var row in model1.Resources)
{
Bugscount2 = Bugscount2 + row.Fixedbugs + "," ;
}
foreach (var row in model1.Resources)
{
BugsCount3 = BugsCount3 + row.Reopenedbugs + ",";
}
ComboinedString = ResourceName1 + "/" + BugsCount + "/" + BugsCount1 + "/" + Bugscount2 + "/" + BugsCount3;
return Json(ComboinedString, JsonRequestBehavior.AllowGet);
}
my
ComboinedString =[Anil Kumar K,Niharika,Raghu,/4,0,0,/3,0,0,/1,1,1,/1,0,0,]
but i want this string
ComboinedString =[Anil Kumar K,Niharika,Raghu/4,0,0/3,0,0,/1,1,1/1,0,0]
i want to remove this "," before the "/" in this strin or replace it..can any one help me
Add this statement
I hope it will help you
String CombinedString1 = CombinedString.Replace(",/", "/");
A simple solution is a search and replace on the string replacing ",/" with "/".
A better solution is, rather than using a for() loop and appending a comma at the end of each value, is use String.Join(). For example, replace:
foreach (var row in model1.Resources)
{
ResourceName1 = ResourceName1 + row.EmployeeName + ",";
}
with
ResourceName1 = string.Join(",", model1.Resources.ToArray())
This will remove the trailing comma.
A simple solution would be to use String.EndsWith() function i.e.
string str = "ksjf,sjsfj,sfs,";
if (str.EndsWith(","))
{
str = str.Remove(str.Length - 1);
}
Off the top of my head, you could try to replace with a simple regular expression:
string input = "dsgd,sdgsdg,dsgsdg,sdg,";
string output = Regex.Replace(input, ",$", "");
//output: "dsgd,sdgsdg,dsgsdg,sdg"
#user1542652's solution is simple and works just as well.

Resources