Archive for category javascript

LiveStream chat-only mode

Recently I’ve taken to participating in a LiveStream of a Sunday School I physically attend. Because I’m there physically I don’t need the video so Here’s what I use to remove the video and expand the chat pane to fill up the resulting free space.

$('.player-wrapper').remove();
$('.chat_wrapper').css('width','100%');
Share/Save

Javascript replace on a capture group

I ran into a problem recently where I needed to perform a regex replace on a string and also manipulate the string captured in a capture group at the same time. What I discovered is that its valid to pass a function as the second argument to the replace function which gets passed the capture groups as arguments 1+

So here’s my code to capture a person’s name and escape it.

story = story.replace(person\.go\?ID=\d+"\s*[^>]*>([^(<)]+)<\/a>/g,function() {
     return 'person.go?ID='+escape(arguments[1].replace(/\./g,''))+'">'+arguments[1]+'';
});

Select distinct for MongoDB

Here is a handy script I’ve been using for MongoDB to retrieve a list of all the fields used in a collection. This uses a map/reduce routine and has to comb over all the documents in a collection so you may want to exercise caution when using this script.

// usage:
// mongo localhost/foo --quiet --eval="var collection='bar';" getcollectionkeys.js
var mr = db.runCommand({
  "mapreduce":collection,
  "map":function() {
    for (var key in this) { emit(key, null); }
  },
  "reduce":function(key, stuff) { return null; }, 
  "out":collection + "_keys"
})

print(db[mr.result].distinct("_id"))

db[collection+"_keys"].drop()

Tags: , , ,

node.js at Facebook

Slides

Tags: , , ,

Fun with jsonselect

One of the strengths of CSS and jQuery is that it provides a common and powerful mechanism known as a selector language for referencing bits of data, especially data whose structure is not exactly known at runtime which makes such an addressing scheme a perfect fit for the often lumpy world of HTML.

Increasingly JSON is being used as a transport medium for data and with the rise of NoSQL solutions, having a selector language for JSON makes a lot of sense when dealing with JSON documents whose structure isn’t deterministic.

JSONSelect provides a good implementation of just such a JSON selector language but after working with it on a project I found myself needing to do more than it allowed me to do. Namely, I wanted 1. to be able to perform a selection and receive matching paths instead of the data contained in those paths and I wanted 2. to be able to modify data specified at a path location in-place.

jsonselect.match(sel, obj, asPath); // Added the asPath flag to return a path instead of the values
jsonselect.forEach(sel, obj, fun, asPath); // Added the same flag to forEach, I use this to 
jsonselect.get(path,obj); // For getting the value using a path
jsonselect.set(path, value, obj); // For setting the value of a path
jsonselect.del(path,root); // For deleting a path

Here is my modified version of jsonselect in case anyone needs help solving the same problems I mentioned above.

Tags: , , , ,

Javascript color gradient calculator

Here is a color calculator I adapted from a friend’s PHP implementation:

Color = function() {
};

Color.hexdec = function(hex_string) {
    hex_string = (hex_string + '').replace(/[^a-f0-9]/gi, '');
    return parseInt(hex_string, 16);
}

Color.dechex = function(number) {
    if (number < 0) {
        number = 0xFFFFFFFF + number + 1;
    }
    return parseInt(number, 10).toString(16);
}

Color.pad = function(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

Color.calcgrad = function(val, color1, color2) {
    
    if(!color1.match(/^#[0-9a-f]{6}/) || !color2.match(/^#[0-9a-f]{6}/)) return 'match err!';
    
    if (val > 1) {
        val = 1;
    }
    if (val < 0) {
        val = 0;
    }
    val = parseFloat(val);
    
    c1 = [Color.hexdec(color1.substr(1,2)), Color.hexdec(color1.substr(3,2)), Color.hexdec(color1.substr(5,2))]; //b
    c2 = [Color.hexdec(color2.substr(1,2)), Color.hexdec(color2.substr(3,2)), Color.hexdec(color2.substr(5,2))]; //r
    
    if (val < .5) {
        delta = [(c2[0] - c1[0]), (c2[1] - c1[1]), (c1[2] - c2[2])];
        arrColor = [c1[0] +1 * 2), c1[1] -2 * 2), c1[2] -3 * 2)];
    }
    return '#'+Color.pad(Color.dechex(arrColor[0]),2)+Color.pad(Color.dechex(arrColor[1]),2)+Color.pad(Color.dechex(arrColor[2]),2);
}
  1. delta[0] * val) * 2), c1[1] + ((delta[1] * val) * 2), c1[2] - ((delta[2] * val) * 2)]; } else { delta = [(c1[0] - c2[0]), (c1[1] - c2[1]), (c1[2] - c2[2])]; arrColor = [c1[0] - ((delta[0] * (val - .5 []
  2. delta[1] * (val - .5 []
  3. delta[2] * (val - .5 []

Tags: , ,

Ext.ux.JSONP for ExtJS 4

Here is a solution for making simple JSONP requests in ExtJS 4

Ext.define('Ext.ux.JSONP', {
    extend: 'Ext.data.ScriptTagProxy',
    alias: 'ux.jsonp',

    createRequestCallback: function(request, operation, callback, scope) {
        var me = this;
        
        return function(response) {
            callback.apply(scope, [response]);
            
            operation.setCompleted();
            operation.setSuccessful();
            me.afterRequest(request, true);
        };
    }
});

Tags: , , , ,

Simple message bus for extjs 4

Here’s a simple message bus/broker I wrote for Ext.js 4

Ext.define('Ext.ux.MessageBroker', {
    extend: 'Ext.util.Observable',

    statics: {
        instance: null,
        setInstance: function(i) {
            this.instance = i;
        },
        sendMessage: function(msg, data) {
            this.fireEvent('message',{"msg":msg,"data":data});
        }
    },

    constructor: function(config){
        this.addEvents({
            "message" : true
        });

        if(config && config.listeners) this.listeners = config.listeners;

        Ext.ux.MessageBroker.superclass.constructor.call(this, config)
    }

}, function() {
    Ext.ux.MessageBroker.setInstance(new Ext.ux.MessageBroker());
});


// Sending a message:
Ext.ux.MessageBroker.sendMessage("load_stock", {"symbol":"INTC"});

// Recieving a message:
Ext.util.Observable.observe(Ext.ux.MessageBroker);
Ext.ux.MessageBroker.on('message', function(msg) {
    console.log('message fired: ',msg);
});

Tags: , ,

Simulating Markers with Tile Layers

Here is a great video I found on Youtube on displaying lots of markers (more than a couple hundred points) through tile layers. He makes some great points, but I like my raphael overlay system I used in the church heatmap project.

Tags: , , ,

Calculate a color gradient in Javascript

Here is a simple Javascript class to calculate the percent of a gradient between two colors given the percent (as a float 0-1) and two colors. Uses functions from php.js.

Color = function() {
};

Color.hexdec = function(hex_string) {
    hex_string = (hex_string + '').replace(/[^a-f0-9]/gi, '');
    return parseInt(hex_string, 16);
}

Color.dechex = function(number) {
    if (number < 0) {
        number = 0xFFFFFFFF + number + 1;
    }
    return parseInt(number, 10).toString(16);
}

Color.pad = function(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

Color.calcgrad = function(val, color1, color2) {
    
    if(!color1.match(/^#[0-9a-f]{6}/) || !color2.match(/^#[0-9a-f]{6}/)) return 'match err!';
    
    if (val > 1) {
        val = 1;
    }
    if (val < 0) {
        val = 0;
    }
    val = parseFloat(val);
    
    c1 = [Color.hexdec(color1.substr(1,2)), Color.hexdec(color1.substr(3,2)), Color.hexdec(color1.substr(5,2))];
    c2 = [Color.hexdec(color2.substr(1,2)), Color.hexdec(color2.substr(3,2)), Color.hexdec(color2.substr(5,2))];
    
    if (val < .< .5) {
        delta = [(c2[0] - c1[0]), (c2[1] - c1[1]), (c1[2] - c2[2])];
        arrColor = [c1[0] +1 * 2), c1[1] -2 * 2), c1[2] -3 * 2)];
    }
    return '#'+Color.pad(Color.dechex(arrColor[0]),2)+Color.pad(Color.dechex(arrColor[1]),2)+Color.pad(Color.dechex(arrColor[2]),2);
}
  1. delta[0] * val) * 2), c1[1] + ((delta[1] * val) * 2), c1[2] - ((delta[2] * val) * 2)]; } else { delta = [(c1[0] - c2[0]), (c1[1] - c2[1]), (c1[2] - c2[2])]; arrColor = [c1[0] - ((delta[0] * (val - .5 []
  2. delta[1] * (val - .5 []
  3. delta[2] * (val - .5 []

Tags: , , ,