I am looking for a widget/jquery plugin/hosted service or similar, that you can drop onto a html-page and it will display and update tweets live that contains a certain hashtag, but only from one or more configurable accounts + moderation to approve other people's tweets with same hashtag.
Think newspaper that wants to live-tweet an event, but have control over what shows up on the page from others.
I have searched, but not found anything suitable - and I am sure it must exist.
Hiya demo http://jsfiddle.net/RGrgM/ or http://jsfiddle.net/RGrgM/show/
I have linked someone (my) tweets with this demo but you can link yours :) I am lazy in twitter anyhooo :P this will help you. It will work with live feeds.
Rest everything is there and you can right click and see the source as well as read below code. B-)
This [link] might come handy: http://boxmodeljunkie.com/create-a-simple-twitter-widget-with-yui-3-and-yql/
:)
D'uh don't forget to accept and up vote innit!
it uses:
<title>Twitter Feed Widget with YUI 3 & YQL - jsFiddle demo</title>
<script type='text/javascript' src='/js/lib/yui-min-3.2.0.js'></script>
Jquery code
// top-level global namespace
YUI.namespace('CIF');
// accepts a tweet timestamp and produces relational time text
YUI.CIF.relativeTime = function ( c ) {
var origStamp = Date.parse( c ),
curDate = new Date(),
currentStamp = curDate.getTime(),
difference = parseInt( ( currentStamp - origStamp ) / 1000, 10 ),
dateArr = c.toString().split(' ');
// if no difference, do nothing
if ( difference < 0 ) {
return false;
}
if ( difference <= 5 ) {
return "Just now";
}
if ( difference <= 20 ) {
return "Seconds ago";
}
if ( difference <= 60 ) {
return "A minute ago";
}
if ( difference < 3600 ) {
return parseInt( difference / 60, 10 ) + ' minutes ago';
}
if (difference <= 1.5 * 3600) {
return "One hour ago";
}
if ( difference < 23.5 * 3600 ) {
return Math.round( difference / 3600 ) + ' hours ago';
}
if (difference < 1.5*24*3600) {
return "One day ago";
}
// produce date stamp for tweets older than a day
return dateArr[3].replace( /\:\d+$/,'' ) + ' ' + dateArr[2] + ' ' + dateArr[1] + dateArr[5] !== curDate.getFullYear().toString() ? ' ' + dateArr[5] : '';
};
// load required modules and set up YUI instance
YUI().use( 'node', 'substitute', 'yql', function ( Y ) {
var n = Y.one( '#twitterFeed' ),
// accepts a YQL JSON result object and produces a list of
// tweets using Y.substitute for templating
formatTwitterFeed = function ( r ) {
if (r) {
var s = r.query.results.statuses.status,
// HTML markup template
t = '<li><span class="status-text">{sText}</span> <span ' +
'class="quiet status-time">{sTime}</span></li>',
l = s.length,
f = '<ul>',
i;
for ( i = 0; i < l; i++ ) {
// Y.substitute method to merge HTML markup and result object
f += Y.substitute( t, {
// convert usernames, hash tags and URLs to links
sText : s[i].text
.replace(/(http\S+)/i,'$1')
.replace(/(#)([a-z0-9_\-]+)/i,
'$1$2')
.replace(/(#)(\S+)/ig,
'<a href="http://search.twitter.com/search' +
'?q=%23$2" target="_blank">$1$2</a>'),
sTime : YUI.CIF.relativeTime( s[i].created_at )
} );
}
f += '</ul>';
f += '<a class="button" href="http://twitter.com/tats_innit" title="Follow #Tats_innit on Twitter" target="_blank">Follow on Twitter »</a>';
// append output to target parent node
n.append( f );
}
};
// YQL Twitter query limited to five results for a specified username
Y.YQL( 'select * from twitter.user.timeline( 5 ) ' +
'where screen_name="#tats_innit"', formatTwitterFeed );
});
Related
I've rigged up a simple JS gallery to implement "deep linking" allowing a URL with a hash like #slide-3 to automatically load the gallery with the third slide active. There's an ad in the gallery every seventh slide. These ad slides aren't tracked so the hash becomes #slide-x followed by an image slide, i.e. #slide-7.]
I've created a helper function to convert the slide numbers from the hash into the 0-indexed slide number, taking into account these ads every seventh slide, but was curious if anyone could think of a more graceful way to calculate the proper index as my implementation looks way too complicated to my eye:
var slideNum = parseInt( window.location.hash.replace( '#slide-', '' ), 10 );
slideNum += Math.floor( ( slideNum + Math.floor( slideNum / 7 ) ) / 7 ) - 1;
return slideNum;
That works but having two floors seems like overkill. There must be a simpler way! I'm not sure of the algebraic rules that govern the floor operation however so I can't figure out how to expand/simplify myself. Any help would be appreciated.
I've included a basic JS fiddle which outputs values for the first 36 slides compared to their proper values. Feel free to change the testFunc with your solution and see if works!
var nums = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36];
var correct = [0,1,2,3,4,5,7,8,9,10,11,12,14,15,16,17,18,19,21,22,23,24,25,26,28,29,30,31,32,33,35,36,37,38,39,40];
var testFunc = function( n ) {
var offset = ( n + Math.floor( n / 7 ) ) / 7;
return n + Math.floor( offset ) - 1;
};
document.getElementById('text').innerHTML += 'Input Expected Output<br/>';
for( var i = 0; i < nums.length; i++ ) {
document.getElementById('text').innerHTML += nums[i] + ' ' + correct[i] + ' ' + testFunc( nums[i] ) + '<br/>';
if ( ( i + 1 ) % 6 === 0 ) {
document.getElementById('text').innerHTML += 'AD<br/>';
}
}
<div id="text"></div>
Yes, one integer division is enough:
var testFunc = function( n ) {
n = n - 1;
return Math.floor(n / 6) + n
};
Realized we have both indices on each slide element so I can simply select using the URL index and get the true slide index from the DOM. Still a fun problem to think about perhaps!?
I am using the following Javascript to display my Instagram follower count on my site.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
/*
Get access token & ID through http://jelled.com/instagram/access-token
Register your app here # Instagram http://instagram.com/developer
*/
$(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: true,
url: "https://api.instagram.com/v1/users/{ID}/?access_token={ACCES_TOKEN}",
success: function(data) {
var ig_count = data.data.counts.followed_by.toString();
ig_count = add_commas(ig_count);
$(".instagram_count").html(ig_count);
}
});
function add_commas(number) {
if (number.length > 3) {
var mod = number.length % 3;
var output = (mod > 0 ? (number.substring(0, mod)) : '');
for (i = 0; i < Math.floor(number.length / 3); i++) {
if ((mod == 0) && (i == 0)) {
output += number.substring(mod + 3 * i, mod + 3 * i + 3);
} else {
output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
}
}
return (output);
} else {
return number;
}
}
});
</script>
<span class="instagram_count"> </span>
As you can see, there is a function to add comma's where necessary. I'd like to also display the follower count abbreviated, for example, 3,291 followers as 3.2k, in another class. So keeping the full follower count in one class and the abbreviated in another. I am not the greatest at JavaScript but am slowly learning.
I have found a similar question (Is there a way to round numbers into a reader friendly format? (e.g. $1.1k)) but have had no luck implementing it into my JavaScript.
Any help is greatly appreciated.
function intlFormat(num)
{
return new Intl.NumberFormat().format(Math.round(num*10)/10);
}
function makeFriendly(num)
{
if(num >= 1000000)
return intlFormat(num/1000000)+'M';
if(num >= 1000)
return intlFormat(num/1000)+'k';
return intlFormat(num);
}
Yields:
makeFriendly(1234567)
"1.2M"
makeFriendly(123457)
"123.5k"
makeFriendly(1237)
"1.2k"
makeFriendly(127)
"127"
Intl is the Javascript standard 'package' for implemented internationalized behaviours. Intl.NumberFormatter is specifically the localized number formatter. So this code actually respects your locally configured thousands and decimal separators.
const formatter = new Intl.NumberFormat('en-GB', {
notation: "compact",
compactDisplay: "short"
})
console.log(formatter.format(9876))
output 9.9K
Credit : mdn
Here is a js code to rank items according to Reddit's ranking algorithm.
My question is: how do I use this code to rank my mongodb documents ?
(Reddit's ranking algorithm)
function hot(ups,downs,date){
var score = ups - downs;
var order = log10(Math.max(Math.abs(score), 1));
var sign = score>0 ? 1 : score<0 ? -1 : 0;
var seconds = epochSeconds(date) - 1134028003;
var product = order + sign * seconds / 45000;
return Math.round(product*10000000)/10000000;
}
function log10(val){
return Math.log(val) / Math.LN10;
}
function epochSeconds(d){
return (d.getTime() - new Date(1970,1,1).getTime())/1000;
}
Well you can use mapReduce:
var mapper = function() {
function hot(ups,downs,date){
var score = ups - downs;
var order = log10(Math.max(Math.abs(score), 1));
var sign = score>0 ? 1 : score<0 ? -1 : 0;
var seconds = epochSeconds(date) - 1134028003;
var product = order + sign * seconds / 45000;
return Math.round(product*10000000)/10000000;
}
function log10(val){
return Math.log(val) / Math.LN10;
}
function epochSeconds(d){
return (d.getTime() - new Date(1970,1,1).getTime())/1000;
}
emit( hot(this.ups, this.downs, this.date), this );
};
And the run the mapReduce (without a reducer):
db.collection.mapReduce(
mapper,
function(){},
{
"out": { "inline": 1 }
}
)
And of course presuming that your "collection" has the fields for ups, downs and date. Of course the "rankings" need to be emitted in a way that is "unique" otherwise you need a "reducer" to sort out the results.
But generally speaking that should do the job.
Theres a problem with your function:
new Date(1970, 1, 1) // Sun Feb 01 1970 00:00:00 GMT-0300 (BRT)
Yep, month 1 is February, and it uses the systems timezone as well.
Epoch in JavaScript is
var epoch = new Date(Date.UTC(1970, 0, 1))
Since
epoch.getTime() // 0
The function
function epochSeconds(d){
return (d.getTime() - new Date(1970,1,1).getTime())/1000;
}
should be just
function epochSeconds(d){
return d.getTime()/1000;
}
Compressing a bit, this returns exactly the same results as the python function in http://amix.dk/blog/post/19588
function hot (ups, downs, date){
var score = ups - downs;
var order = Math.log(Math.max(Math.abs(score), 1)) / Math.LN10;
var sign = score > 0 ? 1 : score < 0 ? -1 : 0;
var seconds = (date.getTime()/1000) - 1134028003;
var product = order + sign * seconds / 45000;
return Math.round(product*10000000)/10000000;
}
i have this two recursive functions in javascript.
first function returns digits of the input number in right to left order
second function returns them in left to right order.
function first(n){
if(n > 0){
m = Math.floor( n/10 );
v = ( n - m * 10 ) + " " + first(m);
return v;
}
return "";
}
function second(n){
if(n > 0){
m = Math.floor( n/10 );
v = second(m) + " " + ( n - m * 10 );
return v;
}
return "";
}
result of the first function is
7 6 1
result of the second function is
1 16 167
but I expected this
1 6 7
I tested similar code in PHP and JAVA and it works well.
Presumably the problem is in Javascript's closures. But I cant figure how to fix it.
It's perfectly simple: You're using implied globals:
function second(n)
{
if(n > 0)
{
m = Math.floor( n/10 );
//m is changing here ------\\will use lowest value of m
v = second(m) + " " + ( n - m * 10 );
return v;
}
return "";
}
The fix is:
function second(n)
{
if(n > 0)
{
//make declare it in the scope itself
var m = Math.floor( n/10 );
v = second(m) + " " + ( n - m * 10 );
return v;
}
return "";
}
This still leaves you with the evil implied global v, too. If I were you, I'd declare v locally, too
function second(n)
{
var m, v = '';
n = +(n);//coerce to number
if (n > 0)
{
m = Math.floor(n/10);
v = second(m) + ' '+ (n-m*10);
}
return v;
}
This function works as expected.
The problem didn't really have to do with closures as such, but it was caused by the way JS resolves expressions/names.
Couple that to how JS deals with recursive functions and you get the output you got, plain and simple.
JS doesn't really have a recursive call-stack, yet. Last time I checked, recursive calls were effectively short-circuited (~= goto's). I remember reading something on the subject by Douglas Crockford, about it having something to do with the call-stack.
Though ES5's strict mode does introduce TCO, and it should make it by the end of 2013 (ES6 - Harmony). I've linked to a couple of sites here, if you care to read more on the matter
I have object like this:
{
Name: "John"
Location: "Unknown"
Type: "Unknown"
Status: "Unknown"
Phone_number: "Unknown"
}
Need to format it like this (with tabs or spaces):
Name: John // three tabs
Location: Unknown // two tabs
Type: Unknown // three tabs
Status: Unknown // three tabs
Phone_number: Unknown // one tab
Java and Perl has this functionality in printf, but how to do this in javascript?
Ok. Found here:
/**
* object.padding(number, string)
* Transform the string object to string of the actual width filling by the padding character (by default ' ')
* Negative value of width means left padding, and positive value means right one
*
* #param number Width of string
* #param string Padding chacracter (by default, ' ')
* #return string
* #access public
*/
String.prototype.padding = function(n, c)
{
var val = this.valueOf();
if ( Math.abs(n) <= val.length ) {
return val;
}
var m = Math.max((Math.abs(n) - this.length) || 0, 0);
var pad = Array(m + 1).join(String(c || ' ').charAt(0));
// var pad = String(c || ' ').charAt(0).repeat(Math.abs(n) - this.length);
return (n < 0) ? pad + val : val + pad;
// return (n < 0) ? val + pad : pad + val;
};
This not works with tabs, but works with spaces exactly how I describe in question.
For my example code will be:
$.each(myObj, function(myKey, myVal) {
myOut += myKey.padding(20) + " = " + myVal + "\r\n";
});
Output will be:
Name = John
Location = Unknown
Type = Unknown
Status = Unknown
Phone_number = Unknown
The String.prototype.padEnd(targetLength, padString) method will do the job, it is documented here.
The padString parameter is set to a single-space string if omitted.
Example:
console.log(` ${'Player'.padEnd(19)} ` +
`${'MATCH'.padEnd(8) } ` +
`${'SCORE'.padEnd(8) } `
);
for (const player of this.players) {
console.log(` - ${player.name.padEnd(20)} ` +
`${player.matches.length.toString().padEnd(8) } ` +
`${player.score.toString().padEnd(8) } `
);
}
Result:
Player MATCH SCORE
- Bradly 5 15
- Sam 4 9
- Dew 3 5
EDIT You can add more tabs by using '\t'. Each '\t' means one tab, so in the console.log you can use more console.log(prop + ":\t\t\t" + obj[prop]);
Pass your object to this function (this works for any object):
function printObject(obj)
for(var prop in obj){
if (obj.hasOwnProperty(prop)) {
console.log(prop + ":\t" + obj[prop]);
}
}
You can also get a pretty similar output (but with quotes) by using
JSON.stringify(obj, null, 2);
This will basically print your objects in jason format and will use the last argument (the 2) as the number of separator spaces.