Twitter and jQuery , render tweeted links - ajax

I am using jquery ajax to pull from the twitter api, i'm sure there's a easy way, but I can't find it on how to get the "tweet" to render any links that were tweeted to appear as a link. Right now it's only text.
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts&rpp=2',
success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
UPDATE:
The following function (plugin) works perfectly.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 100,
fadeSpeed : 500,
tweetName: 'jquery'
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q="+settings.tweetName+"&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
Within my Ready Statement :
$.socialFader({ tweetHolder:"#twitter", tweetName:"nettuts", tweetCount:2 });

Here is a plugin I wrote which really simplifies the tweet/json aggregation then parsing. It fades the tweets in and out. Just grab the needed code. Enjoy.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=jquery&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);

You need to parse the tweet content, find the urls and then put them in between yourself.

Unfortunately, at the moment, the search API doesn't have the facility to break out tweet entities (i.e., links, mentions, hashtags) like some of the REST API methods. So, you could either parse out the entities yourself (I use regular expressions) or call back into the rest API to get the entities.
If you decide to call back into the REST API, and once you have extracted the status ID from the search API results, you would make a call to statuses/show like the following:
http://api.twitter.com/1/statuses/show/60183527282577408.json?include_entities=true
In the resultant JSON, notice the entities object.
"entities":{"urls":[{"expanded_url":null,"indices":[68,88],"url":"http:\/\/bit.ly\/gWZmaJ"}],"user_mentions":[],"hashtags":[{"text":"wordpress","indices":[89,99]}]}
You can use the above to locate the specific entities in the tweet (which occur between the string positions denoted by the indices property) and transform them appropriately.
If you prefer to parse the entities yourself, here are the (.NET Framework) regular expressions I use:
Link Match Pattern
(?:<\w+.*?>|[^=!:'"/]|^)((?:https?://|www\.)[-\w]+(?:\.[-\w]+)*(?::\d+)?(?:/(?:(?:[~\w\+%-]|(?:[,.;#:][^\s$]))+)?)*(?:\?[\w\+%&=.;:-]+)?(?:\#[\w\-\.]*)?)(?:\p{P}|\s|<|$)
Mention Match Pattern
\B#([\w\d_]+)
Hashtag Match Pattern
(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)
Twitter also provides an open source library that helps capture Twitter-specific entities like links, mentions and hashtags. This java file contains the code defining the regular expressions that Twitter uses, and this yml file contains test strings and expected outcomes of many unit tests that exercise the regular expressions in the Twitter library.
How you process the tweet is up to you, however I process a copy of the original tweet, and pull all the links first, replacing them in the copy with spaces (so as not to modify the string length.) I capture the start and end locations of the match in the string, along with the matched content. I then pull mentions, then hashtags -- again replacing them in the tweet copy with spaces.
This approach ensures that I don't find false positives for mentions and hashtags in any links in the tweet.

I slightly modified previous one. Nothing lefts after all tweets disappears one by one.
Now it checks if there is any visible tweets and then refreshes tweets.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=istanbul&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$(settings.tweetHolder).find('li.cycles').remove();
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
if (jQuery('#twitter ul li.cycles:visible').length==1) {
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
}
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
jQuery(document).ready(function(){
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
});

Related

Not real random function in a Blogger widget, it always shows 'neighbor' posts from the past

My blog is 12 years old, I have more than 5000 posts. I am using a widget that shows random posts from a specific label. I set it to show 2 posts in the sidebar, and I noticed that these posts are always 'neighbors', which means they are always from the same month in the past. For example, it's always 2 posts from May 2014, or June 2018. It's never something like: 1 post from May 2014 and the other from June 2018. Do you have any idea what the problem is?
Here is the part of the code which (I believe) contains the mistake:
rand=Math.floor((Math.random()*_vRiO.total_entry)+1);
if(rand+bcd140526_post_count>_vRiO.total_entry){
rand=_vRiO.total_entry-bcd140526_post_count+1;
}
if(rand<1){
rand=1;
}
var _vXsM=HOST+_s7IgU[159];
if(bcd140526_index_label){
_vXsM+=_s7IgU[160]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[161]+bcd140526_post_count+_s7IgU[162]+rand+_s7IgU[163];
_fIoT(_vXsM);
}else{
_fYbP(json);
}
}
var _vXsM=HOST+_s7IgU[164];
if(bcd140526_index_label){
_vXsM+=_s7IgU[165]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[166];
if(bcd140526_sort_by==_s7IgU[167]){
_vXsM+=_s7IgU[168];
}else{
_vXsM+=_s7IgU[169]+bcd140526_post_count;
}
_vXsM+=_s7IgU[170];_fIoT(_vXsM);
I can't paste the whole code, the website doesn't let me. But you can get it here: https://sneeit.com/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget/
My settings:
Post Count - 2
Post Order - Random
Specific Label - Summer
Show Thumbnail - Checked
Thumbnail Size - 200
Show Label - No
Show Comment Numbers - No
Show Date - No
Show Author Name - No
Show Readmore - No
Show Snippet - No
Show Copyright - No
Design Style - List
I have painstakingly deobfuscated this extension to be able to check how you could modify it (which should be much easier for you if you still want to), and I see that getting "non-neighbor" random numbers is not what this system is designed to do. choosePost(json) chooses one post by number to be the starting post, and makeWidget (which, bizarrely, uses string concatenation and document.write to generate the widget) just uses the first post_count posts after the chosen post, so your objective is not (easily) doable.
var show_thumbnail = true;
var show_label = false;
var show_comment_numbers = false;
var show_date = false;
var show_author_name = false;
var show_readmore = false;
var show_snippet = false;
var hide_copyright = true;
var snippet_length = 150;
var post_count = 3;
var thumbnail_size = 140; // v1.5, only effect with list style
var sort_by = 'random'; // latest or random
var index_label = 'summer';
var design_style = 'list'; // list or column
var date_format = 'mm/dd/yyyy';
var lang_readmore = 'Readmore';
var HOST = '';
function sourceJSfile(url) {
document.write('<script type="text/javascript" src="' + url + '"<\/script>');
}
function generateDate(pub_date, format) {
pub_date = pub_date.split('-');
date = new Date(pub_date[0], pub_date[1] - 1, pub_date[2].substring(0, 2));
dd = date.getDate();
mm = date.getMonth() + 1;
yyyy = date.getFullYear();
format = format.replace('dd', dd);
format = format.replace('mm', mm);
format = format.replace('yyyy', yyyy);
return format;
}
function cleanContent(content) {
var tgt = '';
var imgtag = '<img ';
var srctag = 'src="';
var quote = '\"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
index2 = content.indexOf(quote, index1 + srctag.length);
tgt = content.substring(index1 + srctag.length, index2);
}
if (tgt == '') {
imgtag = 'data-thumbnail-src="';
srctag = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0 + imgtag.length);
if (index0 != -1) {
tgt = content.substring(index0 + imgtag.length, index1);
}
}
}
if (tgt == '') {
imgtag = '<iframe ';
srctag = 'src="';
quote = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
if (index0 != -1) {
index2 = content.indexOf(quote, index1 + srctag.length);
if (index0 != -1) {
tgt = content.substring(index1 + srctag.length, index2);
tgt = tgt.replace("http://www.youtube.com/watch?v=", '');
tgt = tgt.replace("http://www.youtube.com/embed/", '');
tgt = tgt.replace('?rel=0', '');
tgt = 'http://img.youtube.com/vi/' + tgt + '/mqdefault.jpg';
}
}
}
}
return tgt;
}
function jsonProcessor(json) {
var data = new Object();
var regex = /<\S[^>]*>/g;
data.id = json.feed.id.$t;
key = 'blog-';
index = data.id.indexOf(key);
data.id = data.id.substring(index + key.length);
data.id = data.id.replace('.comments', '');
data.cate = new Array();
if ('category' in json.feed) {
for (let i = 0; i < json.feed.category.length; i++) {
data.cate[i] = json.feed.category[i].term;
}
}
data.title = '';
if ('title' in json.feed) {
data.title = json.feed.title.$t;
}
data.subtitle = '';
if ('subtitle' in json.feed) {
data.subtitle = json.feed.subtitle.$t;
}
data.admin = new Object();
data.admin.name = 'Anonymous';
data.admin.uri = '';
data.admin.avatar = 'http://img1.blogblog.com/img/anon36.png';
if ('name' in json.feed.author[0]) {
data.admin.name = json.feed.author[0].name.$t;
}
if ('uri' in json.feed.author[0]) {
data.admin.uri = json.feed.author[0].uri.$t;
}
if ('gd$image' in json.feed.author[0]) {
if (json.feed.author[0].gd$image.src != 'http://img1.blogblog.com/img/blank.gif') {
data.admin.avatar = json.feed.author[0].gd$image.src;
}
}
data.total_entry = Number(json.feed.openSearch$totalResults.$t);
data.start_index = Number(json.feed.openSearch$startIndex.$t);
data.item_per_page = Number(json.feed.openSearch$itemsPerPage.$t);
data.entry_number = 0;
if ('entry' in json.feed) {
data.entry_number = json.feed.entry.length;
}
data.entry = new Array();
for (let i = 0; i < data.entry_number; i++) {
data.entry[i] = new Object();
temp = new Object();
entry = json.feed.entry[i];
temp.id = entry.id.$t;
key = 'post-';
index = temp.id.indexOf(key);
temp.id = temp.id.substring(index + key.length);
temp.published = '';
if ('published' in entry) {
temp.published = entry.published.$t;
}
temp.cate = new Array();
if ('category' in entry) {
for (j = 0; j < entry.category.length; j++) {
temp.cate[j] = entry.category[j].term;
}
}
temp.title = '';
if ('title' in entry) {
temp.title = entry.title.$t;
}
temp.content = '';
if ('content' in entry) {
temp.content = entry.content.$t;
}
temp.summary = '';
if ('summary' in entry) {
temp.summary = entry.summary.$t;
}
if (temp.summary == '') {
temp.summary = temp.content.replace(regex, '');
}
if (temp.content == '') {
temp.content = temp.summary;
}
temp.link = '';
temp.reply_label = 'comments';
if ('link' in entry) {
for (j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == 'alternate') {
temp.link = entry.link[j].href;
}
if (entry.link[j].rel == 'replies') {
temp.reply_label = entry.link[j].title;
}
}
}
temp.author = new Object();
temp.author.name = 'Anonymous';
temp.author.uri = '';
temp.author.avatar = 'http://img1.blogblog.com/img/anon36.png';
a0 = entry.author[0];
if ('name' in a0) {
temp.author.name = a0.name.$t;
}
if ('uri' in a0) {
temp.author.uri = a0.uri.$t;
}
if ('gd$image' in a0) {
if (a0.gd$image.src != 'http://img1.blogblog.com/blank.gif') {
temp.author.avatar = a0.gd$image.src;
}
}
temp.thumbnail = '';
if ('media$thumbnail' in entry) {
temp.thumbnail = entry.media$thumbnail.url;
}
temp.reply_number = 0;
if ('thr$total' in entry) {
temp.reply_number = Number(entry.thr$total.$t);
}
temp.reply_label = temp.reply_label.replace(temp.reply_number + ' ', '');
temp.reply_to = '';
temp.reply_json = '';
temp.reply_title = '';
if ('thr$in-reply-to' in entry) {
temp.reply_to = entry['thr$in-reply-to'].href;
temp.reply_json = entry['thr$in-reply-to'].source;
temp.reply_json = temp.reply_json.replace('/default/', '/summary/');
temp.reply_json = temp.reply_json + '?alt=json-in-script';
}
temp.pid = '';
if ('gd$extendedProperty' in entry) {
for (j = 0; j < entry.gd$extendedProperty.length; j++) {
if (entry.gd$extendedProperty[j].name == 'blogger.itemClass') {
temp.pid = entry.gd$extendedProperty[j].value;
}
}
}
temp.pid = temp.pid.replace('pid-', '');
data.entry[i] = temp;
}
return data;
}
if (typeof(jquery_included) == 'undefined') {
jquery_included = false;
}
function jqueryLoader() {
if (typeof(jQuery) == 'undefined') {
if (!jquery_included) {
jquery_included = true;
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js');
scriptEl.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
setTimeout(jqueryLoader, 50);
} else {
if (!($('link[href*="font-awesome.css"]').length)) {
linkEl = document.createElement('link');
linkEl.setAttribute('href', 'http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css');
linkEl.setAttribute('rel', 'stylesheet');
document.head.appendChild(linkEl);
}
}
}
jqueryLoader();
function makeWidget(json) {
var div = '<div style="clear:both!important;float:none;!important;line-height:0!important"></div>';
var jsonOut = jsonProcessor(json);
var docAppend = '';
if (jsonOut.total_entry) {
docAppend += ('<div class="post_feed ' + design_style + ' ' + ((show_thumbnail) ? 'thumb' : 'no-thumb') + '"><ul>');
for (let i = 0; i < jsonOut.total_entry && i < post_count; i++) {
p = jsonOut.entry[i];
docAppend += ('<li class="item item-' + i + '">');
if (!p.thumbnail) {
p.thumbnail = cleanContent(p.content);
}
if (show_thumbnail && p.thumbnail) {
var tgt = p.thumbnail;
if (tgt.indexOf('/s72-c/') != -1){
if (design_style === 'column')
tgt = tgt.replace('/s72-c/', '/s1600/');
else
tgt = tgt.replace('/s72-c/', '/s' + thumbnail_size + '-c/');
} else if (tgt.indexOf('youtube.com') != -1 && tgt.indexOf('/default.') != -1) {
tgt = tgt.replace('/default.', '/mqdefault.');
}
p.thumbnail = tgt;
docAppend += ('<a class="thumbnail" style="width:' + thumbnail_size + 'px;height:' + thumbnail_size + 'px;" href="' + p.link + '"><img src="' + p.thumbnail + '"/></a>');
}
docAppend += '<div class="item-body">';
if (show_label && (typeof(p.cate[0]) != 'undefined')) {
docAppend += ('<a class="cate" href="' + HOST + '/search/label/' + p.cate[0] + '">' + p.cate[0] + '</a>');
}
docAppend += ('<h3 class="title">' + p.title + '</h3>');
if (show_author_name || show_comment_numbers || show_date) {
docAppend += '<div class="meta">';
if (show_author_name) {
docAppend += ('<span class="meta-item author-name"><i class="fa fa-user"></i> ' + p.author.name + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item comment-number"><i class="fa fa-comment"></i> ' + p.reply_number + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item date-time"><i class="fa fa-clock-o"></i> ' + generateDate(p.published, date_format) +'</span>');
}
docAppend += (div + '</div>' + div);
}
if (show_snippet) {
if (p.summary.length > snippet_length) {
p.summary = p.summary.substring(0, snippet_length) + '...';
}
if (show_readmore) {
p.summary += ' ' + lang_readmore + '';
}
docAppend += ('<p class="snippet">' + p.summary + '</p>');
}
docAppend += (div + '</div>' + div);
docAppend += ('</li>');
}
docAppend += ('</ul>');
if (!hide_copyright) {
docAppend += div;
docAppend += '<a target="_blank" class="copyright" href="http://www.sneeit.com/2014/05/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget" style="font-size: 11px!important;text-align:right;visibility: visible;!important;text-indent:0!important;height:auto!important;width:100%!important;position:static!important;color:#999!important;display:block!important;opacity:1!important;">BloggerWidget</a>';
}
docAppend += ('</div>' + div);
} else {
docAppend += '<p><em>Have no posts</em><p>';
}
document.write(docAppend);
}
function choosePost(json) {
if (sort_by == 'random') {
var processedJSON = jsonProcessor(json);
rand = Math.floor((Math.random() * processedJSON.total_entry) + 1);
if (rand + post_count > processedJSON.total_entry) {
rand = processedJSON.total_entry - post_count + 1;
}
if (rand < 1) {
rand = 1;
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script&max-result=' + post_count + '&start-index=' + rand + '&callback=makeWidget';
sourceJSfile(request);
} else {
makeWidget(json);
}
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script';
if (sort_by == 'random') {
request += '&max-results=0';
} else {
request += '&max-results=' + post_count;
}
request += '&callback=choosePost';
sourceJSfile(request);
The modifications will take some work, but the deobfuscated version should be much easier to use. I'd recommend removing jqueryLoader, and to get you started: the API requests are sourceJSfile('/feeds/post/default/-/summer?alt=json-in-script&max-results=1&callback=choosePost'). You'd probably be better off rewriting the thing from scratch than trying to bodge it on top of this code, I think.
PS: This code loads the entire jquery library so it can load some random stylesheet in jqueryLoad.

How to loop 2 Dimensional Array on Google Script

There is a problem with my run time execution in my code. It takes too long to finish, since I have to loop a large amounts of data to look for matching data. I used array on the first loop value though, I don't know how to array the second value without affecting the first array.
Name of the first array : Source
Name of the Second array : Target
Here is my Code:
function inactive_sort_cebu() {
var ss = SpreadsheetApp.openById('169vIeTMLK4zN5VGCw1ktRteCwMToU8eGABFDxg52QBk');
// var sheet = ss.getSheets()[0];// Manila Roster
var sheet2 = ss.getSheets()[1];// Cebu Roster
var column = sheet2.getRange("C1:C").getValues();
var last = column.filter(String).length;
// -----------------------------------------------------------
var ss1 = SpreadsheetApp.openById('153ul2x2GpSopfMkCZiXCjmqdPTYhx4QiOdP5SBYzQkc');
// var sched_sheet = ss1.getSheets()[0];// ScheduledForm_Manila
var sched_sheet2 = ss1.getSheets()[1];// ScheduledForm_Cebu
var column2 = sched_sheet2.getRange("C1:C").getValues();
var last2 = column2.filter(String).length;
//// -------------------------Manila-Roster---------------------------------
var i= 2;
var column3 = sched_sheet2.getRange("J1:J").getValues();
var a = column3.filter(String).length - 1;
// var a = 0;
try{
var source = sched_sheet2.getRange("C2:C").getValues();
for (a;a<=last2;){
/// this is the code that i need to array without affecting the other array which is the source variable
var target = sheet2.getRange("C"+ i).getValue();
if(source[a] == target){
// Get "No Schedule Request data on Cell H
var data = sched_sheet2.getRange("H"+(a+2)).getValue();
// Get "Schedule Request data on Cell F
var data1 = sched_sheet2.getRange("F"+(a+2)).getValue();
var condition_1 = sched_sheet2.getRange("D"+(a+2)).getValue();
var condition_2 = sched_sheet2.getRange("G"+(a+2)).getValue();
var format_Con_2 = Utilities.formatDate(condition_2, 'Asia/Manila', 'm/dd/yyyy');
var condition_3 = sched_sheet2.getRange("K"+ (a+2)).getValue();
var date = new Date();
var date_Manila = Utilities.formatDate(date, 'Asia/Manila', 'm/dd/yyyy');
if(condition_1 == "No Schedule Request" && format_Con_2 <= date_Manila && condition_3 ==""){
sheet2.getRange("AA"+ i).setValue("N - "+ data);
sched_sheet2.getRange("J"+ (a+2)).setValue("Cebu");
sched_sheet2.getRange("K"+ (a+2)).setValue("Done");
a++;
}
else if (condition_1 == "Schedule Request" && format_Con_2 <= date_Manila && condition_3 ==""){
sheet2.getRange("AA"+ i).setValue("Y - "+data1);
sched_sheet2.getRange("J"+ (a+2)).setValue("Cebu");
sched_sheet2.getRange("K"+ (a+2)).setValue("Done");
a++;
}
else{a++;}
i=2;}
else {i++;}
}
This is a simple example of a web app that puts an editable spreadsheet on an HTML Page. Publish as a webapp. I loops through the 2D array that you get when you getValues from the getDataRange() method. In this case I'm just intertwining html into the mix.
Code.gs:
var SSID='SpreadsheetID';
var sheetName='Sheet Name';
function htmlSpreadsheet(mode)
{
var mode=(typeof(mode)!='undefined')?mode:'dialog';
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
//s+='<div id="success"></div>';
s+='</body></html>';
switch (mode)
{
case 'dialog':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
userInterface.append(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
break;
case 'web':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function updateSpreadsheet(i,j,value)
{
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet()
{
var output=htmlSpreadsheet('web');
return output;
}
htmlss.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(successHandler)
.updateSpreadsheet(i,j,value)
}
function successHandler(data)
{
$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="success"></div>

google distance matrix API 3

I have code to calculate distance place to another place using google distance matrix API, but for free its limited just 100 elements per query. So I make code for solve the problem using looping code such as for elements , My code is PHP, javascript , and I parse latitude and longitude data from MySql. Anyone know some error of my code below ? because It don't appear anything if I click calculate button. Actualy I have modifie the code from this URL https://google-developers.appspot.com/maps/documentation/javascript/examples/distance-matrix , And this is my Code :
function hitung (){
service = new google.maps.DistanceMatrixService();
for (m = 0 ; m < l-80 ; m++ ){
asal = originarray[m];
for (n = 0 ; n < l-80 ; n++ ){
tujuan = destarray [n];
calculateDistances();
}
}
}
function calculateDistances() {
//var s = 0;
//for (m = 0 ; m < l-80 ; m++ ){
// asal = originarray[m];
//for (n = 0 ; n < l-80 ; n++ ){
//servicearray[s] = new google.maps.DistanceMatrixService();
//tujuan = destarray [n];
service.getDistanceMatrix(
{
//origins: [origin1, origin2],
// destinations: [destinationA, destinationB],
origins: asal,
destinations: tujuan,
//origins: originarray,
//destinations: destarray,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
// s++;
//}
// }
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
//outputDiv.innerHTML = '';
// deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
// addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
// addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: peta,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
Check if you're receiving a response from Google by logging the response...
function callback(response, status) {
console.log(response);
}

How do I return the XPath of a tag using XUL?

I would like to select the XPath of a tag and the content of the tag, something similar to what Evernote is doing. However, I cannot find any examples. How could this be achieved?
After some research we found this:
function createXPathFromElement(elm) {
var allNodes = document.getElementsByTagName('*');
for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode)
{
if (elm.hasAttribute('id')) {
var uniqueIdCount = 0;
for (var n=0;n < allNodes.length;n++) {
if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
if (uniqueIdCount > 1) break;
};
if ( uniqueIdCount == 1) {
segs.unshift('id("' + elm.getAttribute('id') + '")');
return segs.join('/');
} else {
segs.unshift(elm.localName.toLowerCase() + '[#id="' + elm.getAttribute('id') + '"]');
}
} else if (elm.hasAttribute('class')) {
segs.unshift(elm.localName.toLowerCase() + '[#class="' + elm.getAttribute('class') + '"]');
} else {
for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
if (sib.localName == elm.localName) i++;
};
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
};
};
return segs.length ? '/' + segs.join('/') : null;
}
function lookupElementByXPath(path) {
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(path, document.documentElement, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue;
}

Scroll Events in TouchGridPanel

I am building a mobile application using Sencha Touch 1.0. I need to display report, for that am using grid given by Ext.ux.TouchGridPanel.
It is working fine.
Where as I need to capture Scroll event in Ext.ux.TouchGridPanel.
I have added 'scroll' in bubble event of Dataview.
I am also trying to capture the event after the Dataview created.
But nothing seems to be working. Below is the code which I have changed.
Does anybody has any idea how to capture the start of scroll event?
Thanks in advance.
Ext.ux.TouchGridPanel = Ext.extend(Ext.Panel, {
layout: "fit",
multiSelect: false,
initComponent: function () {
var me = this;
me.items = me.dataview = me.buildDataView();
Ext.ux.TouchGridPanel.superclass.initComponent.call(me);
var store = me.store;
store.on("update", me.dispatchDataChanged, me);
var dataview = me.dataview;
dataview.on('scroll', me.startScroll);
},
dispatchDataChanged: function (store, rec, operation) {
var me = this;
me.fireEvent("storeupdate", store, rec, operation);
},
startScroll: function (scroller, offset) {
console.log('is this event captured???')
var me = this;
me.fireEvent("scroll", this.scroller, offset);
},
buildDataView: function () {
var me = this, colModel = me.colModel, colNum = me.getColNum(false), cellWidth = 100 / colNum,
colTpl = '<div class="x-grid-head">';
colTpl += '<thead><tr class="x-grid-header">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + (col.width - 4) + "%") : '';
colTpl += '<th class="x-grid-cell" ' + width + ' style="' + col.style + '" >' + col.header + '</th>';
}
colTpl += '</tr></thead>';
colTpl += '<tbody ><tpl for="."><tr class="x-grid-row">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + col.width + "%") : '';
colTpl += '<td class="x-grid-cell" style="' + col.style + '" >{' + col.mapping + '}</td>';
}
colTpl += '</tr></tpl></tbody>';
colTpl += '</table></div>'
return new Ext.DataView({
store: me.store,
itemSelector: "tr.x-grid-row",
simpleSelect: me.multiSelect,
scroll: me.scroll,
tpl: new Ext.XTemplate(colTpl,
{
isRowDirty: function (dirty, data) {
return dirty ? "x-grid-row-dirty" : "";
}
}
),
prepareData: function (data, index, record) {
var column,
i = 0,
ln = colModel.length;
var prepare_data = {};
prepare_data.dirtyFields = {};
for (; i < ln; i++) {
column = colModel[i];
if (typeof column.renderer === "function") {
prepare_data[column.mapping] = column.renderer.apply(me, [data[column.mapping], column, record, index]);
} else {
prepare_data[column.mapping] = data[column.mapping];
}
}
prepare_data.isDirty = record.dirty;
prepare_data.rowIndex = index;
return prepare_data;
},
bubbleEvents: [
"beforeselect",
"containertap",
"itemdoubletap",
"itemswipe",
"itemtap",
"selectionchange",
"scroll"
]
});
},
// #private
onScrollStart: function () {
console.log("Are you coming here");
var offset = this.scroller.getOffset();
this.closest = this.getClosestGroups(offset);
this.setActiveGroup(this.closest.current);
},
// #private
onScroll: function (scroller, pos, options) {
}
});
Ext.reg("touchgridpanel", Ext.ux.TouchGridPanel);
We can directly access dataview scroller and check event of the same.
For eg.
newGrid = new Ext.ux.TouchGridPanel({....
after creation of the Panel just access its dataview scroller
newGrid.dataview.scroller.on('scroll', scrollGrid1);
var scrollGrid1 = function(scroller, offsets){
console.log(' Grid scrolling with offset ' + offsets.x + ' & ' + offsets.y);
}

Resources