Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, June 27, 2023

How to lock an object when websocketgateway has many requests mutex

 test.ts

class Mutex {   
    queue: any[];
    queue_args: any[];
    locked: boolean;

    constructor() {
        this.locked = false;
        this.queue = [];
        this.queue_args = [];
    }

    lock(data: any) {
        return new Promise<void>(resolve => {
            if (this.locked) {
                this.queue.push(resolve);
                this.queue_args.push(data);
                console.log('lock', this.queue_args);
            } else {
                this.locked = true;
                resolve();
            }
        });
    }

    unlock() {
        if (this.queue.length > 0) {
            const nextResolver = this.queue.shift();
            const nextArgs = this.queue_args.shift();
            console.log('unlock', nextArgs, this.queue_args);
            nextResolver();
        } else {
            this.locked = false;
        }
    }
}

class WebSocketGateway {
    data: {};
    mutex: Mutex;

    constructor() {
        this.data = {};
        this.mutex = new Mutex();
    }

    async handleRequest(request) {
        await this.mutex.lock(request.data);
        try {
            await new Promise(resolve => setTimeout(resolve, 1000));
        } finally {
            this.mutex.unlock();
        }
    }
}

const gateway = new WebSocketGateway();
for (var i = 0; i < 4; i++)
    gateway.handleRequest({ data: 'request-' + i });

Thursday, June 2, 2016

ajax page for crawler using history.pushState and window.onpopstate

<!DOCTYPE html>
<!-- saved from url=(0045)http://html5doctor.com/demos/history/whiskers -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
  <title>test!</title>
  <style>
    html { background-color:#ddd; }
    body { margin:1em auto; max-width:600px; background-color:#fff; border:solid 1px #aaa; padding:15px; font-family:Georgia,serif; }
    h1 { font-family:Helvetica,Arial,sans-serif; float:left; width:30%; margin:0; }
    nav { display:block; float:right; width:45%;}
    ul { list-style:none; padding:0; margin:0; }
    li { display:inline-block; padding:0; border-right:solid 1px #aaa; margin:.5em 0 0; }
    li:last-child { border-right:0; }
    a { color:rgb(0,144,210); padding:.2em 0.5em; }
    a:hover { text-decoration:none; }
    #content { clear:left; float:left; width:45%; margin-right:10%; line-height:1.4em; }
    #photo { float:right; width:45%; margin-top:1em; }
    .cf:before, .cf:after { content:""; display:table; }
    .cf:after { clear:both; }
  </style>
</head>

<body class="cf">
  <h1>test!</h1>

  <nav>
    <ul class="cf">
      <li><a href="/fluffy">Fluffy</a></li>
      <li><a href="/socks">Socks</a></li>
      <li><a href="/whiskers">Whiskers</a></li>
      <li><a href="/bob">Bob</a></li>
    </ul>
  </nav>

  <p id="content">content!</p>

  <img src="" alt="A heartbreakingly cute kitten!" id="photo">

  <script>
    // Not the most elegant code but fit enough for this example. Enjoy the kitten goodness!
    var contentEl = document.getElementById('content'),
        photoEl = document.getElementById('photo'),
        linkEls = document.getElementsByTagName('a'),
        cats = {
          fluffy: {
            content: 'Fluffy!',
            photo: 'http://placekitten.com/200/200'
          },
          socks: {
            content: 'Socks!',
            photo: 'http://placekitten.com/280/280'
          },
          whiskers: {
            content: 'Whiskers!',
            photo: 'http://placekitten.com/350/350'
          },
          bob: {
            content: 'Just Bob.',
            photo: 'http://placekitten.com/320/270'
          }
        };

    // Switcheroo!
    function updateContent(data) {
      if (data == null)
        return;

      contentEl.textContent = data.content;
      photoEl.src = data.photo;
    }

    // Attach event listeners
    for (var i = 0, l = linkEls.length; i < l; i++) {
      linkEls[i].addEventListener('click', function (event) {
      var cat = event.target.getAttribute('href').split('/').pop();
 var data = cats[cat] || null; // In reality this could be an AJAX request

      updateContent(data);

      // Add an item to the history log
 document.title = event.target.textContent;
      history.pushState(data, event.target.textContent, event.target.href);

      return false;
    });
    }

    // Revert to a previously saved state
    window.addEventListener('popstate', function(event) {
      console.log('popstate fired!');

      updateContent(event.state);
    });

    // Store the initial content so we can revisit it later
    history.replaceState({
      content: contentEl.textContent,
      photo: photoEl.src
    }, document.title, document.location.href);
  </script>



</body></html>

Thursday, September 24, 2015

javascript with jquery core methods for my h2o cms

/*! h2o v1.0.3 | (c) hiimeloyun@gmail.com*/
window.h2o = window.h2o || {
    extend: function (x, y) {
        var self = this;
        if (typeof y !== 'undefined' && y) {
            self = y;
        }
        for (var i in x) {
            self[i] = x[i];
        }
        return self;
    }
};
h2o.extend({
    ajax_locked: false,
    site_protocol: window.location.protocol,
    site_hostname: window.location.hostname,
    jstr: typeof JSON !== "undefined" ? JSON.stringify : function (obj) {
        var arr = [];
        $.each(obj, function (key, val) {
            var next = key + ": ";
            next += $.isPlainObject(val) ? h2o.jstr(val) : val;
            arr.push(next);
        });
        return "{ " + arr.join(", ") + " }";
    },
    postData: function () {
        var r20 = /%20/g;
        //('name','value')
        if (arguments.length === 2) {
            var key = arguments[0];
            var value = arguments[1];
            return encodeURIComponent(key) + "=" + encodeURIComponent(value).replace(r20, "+");
        } else {
            var s = [], add = function (key, value) {
                // If value is a function, invoke it and return its value
                s.push(encodeURIComponent(key) + "=" + encodeURIComponent(value).replace(r20, "+"));
            }, arg = arguments[0];
            //any string
            if (typeof arg === 'string') {
                return encodeURIComponent(arg).replace(r20, "+");
            } else {
                //any container object
                if (!Array.isArray(arg)) {
                    if (typeof arg === 'object' && typeof jQuery !== 'undefined') {
                        arg = $(arg).postItems();
                    }
                }
                //[{name:'name',value:'value'}]
                for (var i = 0; i < arg.length; i++) {
                    add(arg[i].name, arg[i].value);
                }
                return s.join("&").replace(r20, "+");
            }
        }
    }
});
h2o.extend({
    base_url: (function () {
        var myScripts = document.getElementsByTagName('script');
        var myScript = myScripts[myScripts.length - 1];
        var myArgs = myScript.src.split('?');
        var myModule = '';
        if (myArgs.length > 1) {
            myModule = myArgs[1];
        }
        var host = h2o.site_hostname;
        var baseurl = h2o.site_protocol + '//' + host;
        var fip = host.split('.')[0];
        var isip = (0 < fip && fip < 256);
        if (isip === false && host.indexOf('.') > 0) {
            baseurl = baseurl + (myModule.length > 0 ? '/' + myModule : '');
        } else {
            var jssrc = myArgs[0];
            var jssrc_seg = jssrc.split('/');
            var rootfolder = jssrc_seg[3];
            baseurl = baseurl + (rootfolder.length > 0 ? '/' + rootfolder : '');
        }
        return baseurl;
    })()
});
h2o.extend({
    viewResult: function (result, into) {
        if (typeof into === 'object') {
            if ($(into).prop('tagName') === 'UL') {
                $('<li/>').appendTo($(into)).html(result).hide().fadeIn('slow').refreshLayout();
            } else {
                $(into).html(result).hide().fadeIn('slow').refreshLayout();
            }
        } else if (typeof into === 'function') {
            into(result);
        }
    },
    get: function (link, into, responseType) {
        if (typeof responseType === 'undefined' || !responseType) {
            responseType = 'html';
        }
        $.ajax({
            type: 'get',
            dataType: responseType,
            url: link,
            success: function (result) {
                h2o.viewResult(result, into);
            }, beforeSend: function () {
                if (typeof into === 'object') {
                    $(into).htmlWaiting();
                }
            }, statusCode: {
                404: function () {
                    alert("Веб хаяг олдсонгүй!");
                }
            }
        });
    },
    post: function (link, form, into, responseType) {
        if (h2o.ajax_locked) {
            alert('Та түр хүлээнэ үү!');
            return;
        }
        h2o.ajax_locked = true;
        if (typeof responseType === 'undefined' || !responseType) {
            responseType = 'html';
        }
        if (typeof form === 'undefined' || !form) {
            form = link;
            link = ($(form).prop('tagName') === 'FORM') ? form.attr('action') : form.attr('data-action');
        }
        var sendParams = null;
        if (typeof form === 'string') {
            sendParams = form;
        } else {
            if ($(form).prop('tagName') === 'FORM')
                sendParams = $(form).serialize();
            else
                sendParams = h2o.postData(form);
        }
        $.ajax({
            type: 'post',
            dataType: responseType,
            url: link,
            data: sendParams,
            success: function (result) {
                h2o.viewResult(result, into);
            }, beforeSend: function () {
                if (typeof into === 'object') {
                    $(into).htmlWaiting();
                }
            }, error: function (request, status, error) {
                alert(request.responseText);
            }, complete: function (result) {
                h2o.ajax_locked = false;
            }
        });
    },
    action: function (link, funcBefore, funcAfter, method, responseType) {
        if (typeof method === 'undefined') {
            method = 'get';
        }
        if (typeof responseType === 'undefined') {
            responseType = 'json';
        }
        $.ajax({
            type: method,
            dataType: responseType,
            url: link,
            cache: false,
            success: function (result) {
                if (funcAfter)
                    funcAfter(result);
                else
                    funcBefore(result);
            }, beforeSend: function () {
                if (funcAfter)
                    funcBefore();
            }, statusCode: {
                404: function () {
                    alert("Веб хаяг олдсонгүй!");
                }
            }
        });
    },
    redirect: function (link) {
        if (window.location.href) {
            window.location.href = link;
        } else {
            window.location = link;
        }
    },
    // window scroll function
    scrollToID: function (id, speed) {
        var offSet = 50;
        var targetOffset = $(id).offset().top - offSet;
        var mainNav = $('#main-nav');
        $('html,body').animate({scrollTop: targetOffset}, speed);
        if (typeof mainNav !== 'undefined' && mainNav.hasClass("open")) {
            mainNav.css("height", "1px").removeClass("in").addClass("collapse");
            mainNav.removeClass("open");
        }
    },
    navlink: function (obj, into) {
        if (typeof into === 'undefined' || !into || into === null) {
            into = h2o.panel();
        }
        return $(obj).each(function () {
            $(this).click(function () {
                h2o.get($(this).attr('href'), into);
                return false;
            });
        });
    },
    set_meta: function (ajson, cjson) {
        /*<meta name="author" content="">*/
        $('title').text(ajson.meta_title + ' - ' + h2o.site_hostname);
        $('meta[name]').each(function (ndx, tag) {
            var name = $(tag).attr('name');
            if (typeof name !== 'undefined') {
                if (name === 'title') {
                    $(tag).attr('content', ajson.meta_title);
                }
                if (name === 'description') {
                    $(tag).attr('content', ajson.meta_description);
                }
                if (name === 'keywords') {
                    var cmeta_title = (typeof cjson !== 'undefined') ? cjson.meta_title : ajson.meta_title;
                    $(tag).attr('content', cmeta_title + ', ' + ajson.meta_keywords + ' - ' + h2o.site_hostname);
                }
                if (name === 'author') {
                    $(tag).attr('content', ajson.meta_author);
                }
            }
        });
    }
});
h2o.extend({
    imgsViewer: function (obj) {
        var fadeDuration = 2000, slideDuration = 4000, currentIndex = 1, nextIndex = 1,
                nextSlide = function () {
                    nextIndex = currentIndex + 1;
                    if (nextIndex > $(obj).children().size()) {
                        nextIndex = 1;
                    }
                    var next = $(obj).find('li:nth-child(' + nextIndex + ')');
                    var curr = $(obj).find('li:nth-child(' + currentIndex + ')');
                    next.addClass('ishow').animate({opacity: 1.0}, fadeDuration);
                    curr.removeClass('ishow').animate({opacity: 0.0}, fadeDuration);
                    currentIndex = nextIndex;
                    setTimeout(nextSlide, slideDuration);
                };
        $(obj).find('li').css({opacity: 0.0});
        $(obj).find('li:nth-child(' + nextIndex + ')')
                .addClass('ishow').animate({opacity: 1.0}, fadeDuration);
        setTimeout(nextSlide, slideDuration);
        return this;
    },
    bgImager: function (arg) {
        var self = this, pane = $('#bg-images'), c = 0, t = 4000, bgi = null, bgis = arg,
                changeBg = function () {
                    if (pane.find('.img').size() > 0) {
                        var prevImg = pane.find('.img').eq(0);
                        bgi.show().insertBefore(prevImg).next().fadeTo(1000, 0, function () {
                            $(this).remove();
                            nextBg();
                        });
                    } else {
                        bgi.appendTo(pane).fadeTo(1000, 1, function () {
                            nextBg();
                        });
                    }
                },
                nextBg = function () {
                    c = Math.RandInt(0, bgis.length);
                    if (c >= bgis.length) {
                        c = 0;
                    }
                    var img = $('<img/>').addClass('img');
                    $(img).load(function () {
                        bgi = $(this).hide();
                        if (pane.find('.img').size() > 0) {
                            setTimeout(changeBg, t);
                        } else {
                            changeBg();
                        }
                    }).attr('src', h2o.base_url + '/' + bgis[c]);
                },
                initBg = function (s) {//s is second
                    if (pane.css('margin-top') === '1px') {
                        return false;
                    }
                    $(window).bind('resize.bgimager', function () {
                        var win_w = $(window).width();
                        pane.find('.img').each(function (index, img) {
                            var img_w = $(img).width();
                            if (img_w >= win_w) {
                                var w = (win_w - img_w) / 2;
                                $(img).css('left', w);
                            }
                        });
                    });
                    t = 1000 * s;
                    nextBg();
                };
        self.init = initBg;
        return this;
    },
    initGmap: function () {
        var googleMaps = google && typeof google !== 'undefined' ? google.maps : 'undefined';
        if (typeof googleMaps !== 'undefined') {
            var self = this.initGmap || h2o.initGmap;
            h2o.extend({mapEditState: false, bounds: []}, self);
            var mapCanvas = document.getElementById('map_canvas');
            var mapInput = document.getElementById('googlemap');
            var latitude = self.bound_lat;
            var longitude = self.bound_lng;
            var marker_latitude = self.marker_lat;
            var marker_longitude = self.marker_lng;
            var bound_Latlng = new googleMaps.LatLng(latitude, longitude);
            var marker_Latlng = new googleMaps.LatLng(marker_latitude, marker_longitude);
            var mapOptions = {
                center: bound_Latlng,
                zoom: self.bound_zoom,
                mapTypeId: googleMaps.MapTypeId.HYBRID
            };
            var map = new googleMaps.Map(mapCanvas, mapOptions);
            var styles = [
                {
                    featureType: "all",
                    elementType: "labels",
                    stylers: [
                        {visibility: "on"}
                    ]
                }
            ];
            map.setOptions({styles: styles});
            var marker = new googleMaps.Marker({
                position: marker_Latlng,
                map: map,
                draggable: true,
                title: "Сонгосон байршил"
                        //icon: 'brown_markerA.png'
            });
            var markedPlaceSave = function () {
                var location = marker.getPosition();
                var zoom = map.getZoom();
                var bounds = map.getBounds();
                var ne = bounds.getNorthEast();
                var sw = bounds.getSouthWest();
                self.bounds = ne.lat() + ',' + ne.lng() + ',' + sw.lat() + ',' + sw.lng()
                        + ',' + zoom + ',' + location.lat() + ',' + location.lng();
                var msg = 'gmb=' + self.bounds;
                if (mapInput) {
                    mapInput.value = self.bounds;
                }
                var latlngSpans = $('#map-usage-body .latlng span');
                latlngSpans.first().html(location.lat());
                latlngSpans.last().html(location.lng());
                if (self.mapEditState) {
                    var link = h2o.base_url + '/zarwrite/gmap?' + msg;
                    h2o.action(link, function (result) {
                        if (result.success) {
                            $('.googlemap .title').html('Байршил: ' + result.data[5] + ', ' + result.data[6]);
                        } else {
                            alert(result.message);
                        }
                    });
                }
            };
            googleMaps.event.addListener(map, 'click', function (event) {
                var location = event.latLng;
                marker.setPosition(location);
                markedPlaceSave();
            });
            googleMaps.event.addListener(marker, 'dragend', function (event) {
                var location = event.latLng;
                marker.setPosition(location);
                markedPlaceSave();
            });
            googleMaps.event.addListener(map, 'bounds_changed', function () {
                try {
                    markedPlaceSave();
                } catch (err) {
                    alert(err);
                }
            });
        }
    },
    reloadCaptchaImg: function (capimg) {
        var link = h2o.base_url + '/captcha/image?' + getTimeAsLong();
        $.ajax({
            url: link,
            success: function (result) {
                var par = capimg.parent();
                capimg.remove();
                capimg = $('<img src="' + result + '"/>');
                capimg.appendTo(par);
                capimg.animate({'opacity': '1'}, {
                    duration: 300
                });
            }
        });
    },
    insertedFileCancel: function (closeSpan) {
        closeSpan.click(function (evt) {
            evt.preventDefault();
            var par = closeSpan.parents('div').first();
            var mid = par.find('a').attr('data-id');
            par.remove();
            var link = h2o.base_url + '/media/deleteFile?fileid=' + mid;
            h2o.action(link, function (result) {
                if (result.error) {
                    alert(result.message);
                }
            });
        });
    },
    initFileUpload: function (fileCtl) {
        'use strict';
        // Change this to the location of your server-side upload handler:
        var url = window.location.hostname === 'blueimp.github.io' ?
                '//jquery-file-upload.appspot.com/' : h2o.base_url + '/media/upload';
        var uploadButton = $('<button/>')
                .addClass('btn btn-primary')
                .prop('disabled', true)
                .text('Processing...')
                .on('click', function () {
                    var $this = $(this), data = $this.data();
                    $this.off('click').text('Abort').on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                    data.submit().always(function () {
                        $this.remove();
                    });
                });
        var maxNumberOfFiles = 8;
        fileCtl.click(function (event) {
            if ($('#files > div').size() >= maxNumberOfFiles) {
                event.preventDefault();
                alert(maxNumberOfFiles + ' -с илүү файл хуулах боломжгүй!');
            }
        });
        try {
            fileCtl.fileupload({
                url: url,
                dataType: 'json',
                autoUpload: true, //false
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                maxFileSize: 5000000, // 5 MB
                limitConcurrentUploads: 1,
                maxNumberOfFiles: maxNumberOfFiles,
                // Enable image resizing, except for Android and Opera,
                // which actually support image resizing, but fail to
                // send Blob objects via XHR requests:
                disableImageResize: /Android(?!.*Chrome)|Opera/
                        .test(window.navigator.userAgent),
                previewMaxWidth: 50,
                previewMaxHeight: 50,
                previewCrop: true
            }).on('fileuploadadd', function (e, data) {
                if ($('#files > div').size() >= maxNumberOfFiles) {
                    alert(maxNumberOfFiles + ' -с илүү файл хуулах боломжгүй!');
                    return false;
                }
                data.context = $('<div/>').appendTo('#files');
                $.each(data.files, function (index, file) {
                    var closeSpan = $('<span/>').text('Болих').prepend($('<i class="glyphicon glyphicon-remove"></i>'));
                    h2o.insertedFileCancel(closeSpan);
                    var node = $('<p/>').attr('title', file.name).append(closeSpan);
                    if (!index) {
                        //node.append('<br>').append(uploadButton.clone(true).data(data));
                    }
                    node.appendTo(data.context);
                });
            }).on('fileuploadprocessalways', function (e, data) {
                var index = data.index,
                        file = data.files[index],
                        node = $(data.context.children()[index]);
                if (file.preview) {
                    node.prepend('<br>').prepend(file.preview);
                }
                if (file.error) {
                    node.append($('<span class="text-danger"/>').text(file.error));
                }
                if (index + 1 === data.files.length) {
                    data.context.find('button').text('Upload').prop('disabled', !!data.files.error);
                }
            }).on('fileuploadprogressall', function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#progress .progress-bar').css('width', progress + '%');
            }).on('fileuploaddone', function (e, data) {
                $.each(data.result.files, function (index, file) {
                    if (file.url) {
                        var link = $('<a>').attr('target', '_blank').attr('data-id', file.id).prop('href', file.url);
                        $(data.context.children()[index]).wrap(link);
                    } else if (file.error) {
                        var error = $('<span class="text-danger"/>').text(file.error);
                        $(data.context.children()[index]).append(error);
                    }
                });
            }).on('fileuploadfail', function (e, data) {
                $.each(data.files, function (index) {
                    var error = $('<span class="text-danger"/>').text('Алдаа!');
                    $(data.context.children()[index]).append(error);
                });
            }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
        } catch (err) {
            alert(err);
        }
    },
    send_contact: function (button) {
        var form = $(button).parents('dl').parent();
        form.find('.label').addClass('hidden');
        h2o.post(h2o.base_url + '/contact/send', form, function (result) {
            if (result.success) {
                $(form).find('.label-success').removeClass('hidden');
                $(form).find('input,textarea').val('');
            } else {
                $(form).find('.label-danger').removeClass('hidden');
                if (result.message) {
                    alert(result.message);
                }
            }
        }
        , 'json');
    }
});
h2o.extend({
    initResBgImages: function () {
        var c_url = h2o.base_url + '/res/images/bg/7200';
        h2o.action(c_url, function (result) {
            h2o.bgImager(result).init(6);
        });
    }
});

Wednesday, September 23, 2015

how to get site base url in javascript

js dotoroo base_url aa avah neg iimerhuu arga baij boloh yum
<?php echo base_url(); ?>
or
base_url: (function () {
        var myScripts = document.getElementsByTagName('script');
        var myScript = myScripts[myScripts.length - 1];
        var myArgs = myScript.src.split('?');
        var myModule = '';
        if (myArgs.length > 1) {
            myModule = myArgs[1];
        }
        var host = window.location.hostname;
        var baseurl = window.location.protocol + '//' + host;
        var fip = host.split('.')[0];
        var isip = (0 < fip && fip < 256);
        if (isip === false && host.indexOf('.') > 0) {
            baseurl = baseurl + (myModule.length > 0 ? '/' + myModule : '');
        } else {
            var jssrc = myArgs[0];
            var jssrc_seg = jssrc.split('/');
            var rootfolder = jssrc_seg[3];
            baseurl = baseurl + (rootfolder.length > 0 ? '/' + rootfolder : '');
        }
        return baseurl;
    })()

Monday, August 10, 2015

year month day check using reg expression example

if (/^([0-9]|[12]\d|3[0-1])$/.test(30) === false) {
    alert('Day is invalid or empty');
}
if (/^([0-9]|[4]\d|1[0-2])$/.test(4) === false) {
    alert('Month is invalid or empty');
}
if (/^(19|20)\d{2}$/.test('1986') === false) {
    alert('Year is invalid or empty');
}

Sunday, July 19, 2015

horinzontal scrolling content using jScrollPane and content mousemove event

var scrollbarWidth = 16;
    var scrollHeight = $('.site-container').get(0).scrollHeight;
    var sw = $(window).width();
    var sh = $(window).height();
    var padleftStr = $('.site-container').css('padding-left');
    var padleftInt = padleftStr.substring(0, padleftStr.length - 2);

    var tnavWidth = sw - (scrollHeight > 0 ? scrollbarWidth : 0) - padleftInt;
    var lnavHeight = sh - $('.logo-wrap').height();

    $(window).on('resize', function () {
        checkScrolling($('.cd-tabs nav'));
        tabContentWrapper.css('height', 'auto');

        sw = $(window).width();
        sh = $(window).height();

        padleftStr = $('.site-container').css('padding-left');
        padleftInt = padleftStr.substring(0, padleftStr.length - 2);

        tnavWidth = sw - scrollbarWidth - padleftInt;
        lnavHeight = sh - $('.logo-wrap').height();
        $('.menu-3 span').html('sw: ' + sw + ' , padleft: ' + padleftInt);

        var toppadleftStr = $('.top-container').css('padding-left');
        var toppadleftInt = toppadleftStr.substring(0, toppadleftStr.length - 2);
        $('.top-container').width(tnavWidth - toppadleftInt - 1);
        $('.top-container #top-navbar-container').width(tnavWidth - toppadleftInt - 1);

        $('.scroll-bar-left').height(lnavHeight - 1);

        $('.scroll-bar-left, #top-navbar-container, .zar-wrapper').each(function () {
            var api = $(this).data('jsp');
            if (typeof api === 'object') {
                api.reinitialise();
            } else {
                $(this).jScrollPane();
            }
        });

        var jspPane = $('#top-navbar-container').find('.jspPane');
        var jspContainer = $('#top-navbar-container').find('.jspContainer');
        if (jspContainer.find('.jspHorizontalBar').size() === 0) {
            jspPane.css('left', '0px');
        }

    }).trigger('resize');

    var toppadleftStr = $('.top-container').css('padding-left');
    var toppadleftInt = toppadleftStr.substring(0, toppadleftStr.length - 2);
    $('.top-container').width(tnavWidth - toppadleftInt - 1);
    $('.top-container #top-navbar-container').width(tnavWidth - toppadleftInt - 1);
    $('.scroll-bar-left').height(lnavHeight - 1);

    $('#top-navbar-container').mousedown(function (event) {
        event.preventDefault();
       
        improvejScrollPane.downx = event.pageX;
        improvejScrollPane.moving = false;
    }).mousemove(function (event) {
        event.preventDefault();

        var jspPane = $(this).find('.jspPane');
        var navfullw = jspPane.find('#navbar').width();
        var jspw = $(this).find('.jspContainer').width();
        var panel = jspPane.position().left;
        var trackw = $(this).find('.jspTrack').width();
        var jspDrag = $(this).find('.jspDrag');
        var dragw = jspDrag.width();
        var dragl = jspDrag.position().left;
        var currx = event.pageX;
        var diffx = improvejScrollPane.downx - currx;
        var clicked = parseInt(event.which + '' + event.button);

        if (improvejScrollPane.downx > 0 && Math.abs(diffx) > 0 && clicked === 10) {
            improvejScrollPane.moving = true;
            improvejScrollPane.downx = currx;

            var ddiffx = diffx * -1;
            var diffw = jspw - navfullw;
            var ddiffw = dragw - trackw;
            var perw = Math.abs(ddiffw / diffw) * diffx;
            var cleft = panel + ddiffx;
            var dleft = dragl + perw;
            if (ddiffx > 0) {
                if (cleft > 0)
                    cleft = 0;
                if (dleft < 0)
                    dleft = 0;
            } else {
                if (cleft < diffw)
                    cleft = diffw;
                if (trackw < dleft + dragw)
                    dleft = trackw - dragw;
            }
            //$('.test').html(diffw + '=>' + ddiffw);
            jspPane.css('left', cleft + 'px');
            jspDrag.css('left', dleft + 'px');
        }
    }).mouseup(function (event) {
        event.preventDefault();
        improvejScrollPane.downx = 0;
    }).click(function (event) {
        if (improvejScrollPane.moving)
            event.preventDefault();
    });

Wednesday, June 17, 2015

php codeigniter facebook javascript sdk example

<script>

        window.fbAsyncInit = function () {
            FB.init({
                appId: '<?php echo config_item('facebook_app_id'); ?>',
                cookie: true, // enable cookies to allow the server to access
                // the session
                xfbml: true, // parse social plugins on this page
                version: 'v2.2' // use version 2.2
            });
            FB.getLoginStatus(function (response) {
                statusChangeCallback(response);
            });
        };

        // Load the SDK asynchronously
        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id))
                return;
            js = d.createElement(s);
            js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

        function statusChangeCallback(response) {
            console.log('statusChangeCallback');
            console.log(response);

            if (response.status === 'connected') {
                // Logged into your app and Facebook.
                getFbUserInfo(response);
            } else if (response.status === 'not_authorized') {
                // The person is logged into Facebook, but not your app.
                document.getElementById('fbstatus').innerHTML = 'Please log ' +
                        'into this app.';
            } else {
                // The person is not logged into Facebook, so we're not sure if
                // they are logged into this app or not.
                if (response.status !== 'unknown') {
                    document.getElementById('fbstatus').innerHTML = 'Please log ' +
                            'into Facebook.';
                }
            }
        }

        function getFbUserInfo(auth) {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function (me) {
                console.log('Successful login for: ' + me.name);

                $('#fbstatus').text('Үйлчлүүлсэнд баярлалаа, ' + me.name + '!').show();

                $.ajax({
                    type: "post",
                    url: "<?php echo site_url('api/auth/login'); ?>",
                    data: 'email=' + me.email + "&name=" + me.name + "&access=" + auth.authResponse.accessToken,
                    beforeSend: function () {
                        $('#loading').show();
                        alert(auth.authResponse.accessToken);
                    }
                }).done(function (data) {
                    $('#loading').hide('slow');
                    alert(data);
                });
            });
        }

        $(document).ready(function () {
//            setTimeout(function () {
//                $('.fb-login-button').show();
//            }, 2000);
        });
    </script>

Wednesday, April 15, 2015

TypeScript vs ProtoType syntax

Inheritance


class Animal {
    constructor(public name: string) { }
    move(meters: number) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);


TO JS


var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    Animal.prototype.move = function (meters) {
        alert(this.name + " moved " + meters + "m.");
    };
    return Animal;
})();
var Snake = (function (_super) {
    __extends(Snake, _super);
    function Snake(name) {
        _super.call(this, name);
    }
    Snake.prototype.move = function () {
        alert("Slithering...");
        _super.prototype.move.call(this, 5);
    };
    return Snake;
})(Animal);
var Horse = (function (_super) {
    __extends(Horse, _super);
    function Horse(name) {
        _super.call(this, name);
    }
    Horse.prototype.move = function () {
        alert("Galloping...");
        _super.prototype.move.call(this, 45);
    };
    return Horse;
})(Animal);
var sam = new Snake("Sammy the Python");
var tom = new Horse("Tommy the Palomino");
sam.move();

tom.move(34);


Generics


class Greeter<T> {
    greeting: T;
    constructor(message: T) {
        this.greeting = message;
    }
    greet() {
        return this.greeting;
    }
}

var greeter = new Greeter<string>("Hello, world");

var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
}

document.body.appendChild(button);


TO JS


var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return this.greeting;
    };
    return Greeter;
})();
var greeter = new Greeter("Hello, world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
};
document.body.appendChild(button);


Modules


module Sayings {
    export class Greeter {
        greeting: string;
        constructor(message: string) {
            this.greeting = message;
        }
        greet() {
            return "Hello, " + this.greeting;
        }
    }
}
var greeter = new Sayings.Greeter("world");

var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
    alert(greeter.greet());
};

document.body.appendChild(button);


TO JS


var Sayings;
(function (Sayings) {
    var Greeter = (function () {
        function Greeter(message) {
            this.greeting = message;
        }
        Greeter.prototype.greet = function () {
            return "Hello, " + this.greeting;
        };
        return Greeter;
    })();
    Sayings.Greeter = Greeter;
})(Sayings || (Sayings = {}));
var greeter = new Sayings.Greeter("world");
var button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function () {
    alert(greeter.greet());
};
document.body.appendChild(button);


New Features


type NameOrNameArray = string | string[];

function createName(name: NameOrNameArray) {
    if (typeof name === "string") {
        return name;
    }
    else {
        return name.join(" ");
    }
}

var greetingMessage = `Greetings, ${createName(["Sam", "Smith"]) }`;
alert(greetingMessage);


TO JS


function createName(name) {
    if (typeof name === "string") {
        return name;
    }
    else {
        return name.join(" ");
    }
}
var greetingMessage = "Greetings, " + createName(["Sam", "Smith"]);
alert(greetingMessage);


examples for all


class Vector {

    constructor(public x: number, public y: number, public z: number) { }

    static times(k: number, v: Vector) {
        return new Vector(k * v.x, k * v.y, k * v.z);
    }

    static minus(v1: Vector, v2: Vector) {
        return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
    }

    static plus(v1: Vector, v2: Vector) {
        return new Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
    }

    static dot(v1: Vector, v2: Vector) {
        return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
    }

    static mag(v: Vector) {
        return Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
    }

    static norm(v: Vector) {
        var mag = Vector.mag(v);
        var div = (mag === 0) ? Infinity : 1.0 / mag;
        return Vector.times(div, v);
    }

    static cross(v1: Vector, v2: Vector) {
        return new Vector(v1.y * v2.z - v1.z * v2.y,
                          v1.z * v2.x - v1.x * v2.z,
                          v1.x * v2.y - v1.y * v2.x);
    }

}

class Color {

    constructor(public r: number, public g: number, public b: number) { }

    static scale(k: number, v: Color) {
        return new Color(k * v.r, k * v.g, k * v.b);
    }

    static plus(v1: Color, v2: Color) {
        return new Color(v1.r + v2.r, v1.g + v2.g, v1.b + v2.b);
    }

    static times(v1: Color, v2: Color) {
        return new Color(v1.r * v2.r, v1.g * v2.g, v1.b * v2.b);
    }

    static white = new Color(1.0, 1.0, 1.0);
    static grey = new Color(0.5, 0.5, 0.5);
    static black = new Color(0.0, 0.0, 0.0);
    static background = Color.black;
    static defaultColor = Color.black;

    static toDrawingColor(c: Color) {
        var legalize = d => d > 1 ? 1 : d;
        return {
            r: Math.floor(legalize(c.r) * 255),
            g: Math.floor(legalize(c.g) * 255),
            b: Math.floor(legalize(c.b) * 255)
        }
    }

}

class Camera {

    forward: Vector;
    right: Vector;
    up: Vector;

    constructor(public pos: Vector, lookAt: Vector) {
        var down = new Vector(0.0, -1.0, 0.0);
        this.forward = Vector.norm(Vector.minus(lookAt, this.pos));
        this.right = Vector.times(1.5, Vector.norm(Vector.cross(this.forward, down)));
        this.up = Vector.times(1.5, Vector.norm(Vector.cross(this.forward, this.right)));
    }

}

interface Ray {
    start: Vector;
    dir: Vector;
}

interface Intersection {
    thing: Thing;
    ray: Ray;
    dist: number;
}

interface Surface {
    diffuse: (pos: Vector) => Color;
    specular: (pos: Vector) => Color;
    reflect: (pos: Vector) => number;
    roughness: number;
}

interface Thing {
    intersect: (ray: Ray) => Intersection;
    normal: (pos: Vector) => Vector;
    surface: Surface;
}

interface Light {
    pos: Vector;
    color: Color;
}

interface Scene {
    things: Thing[];
    lights: Light[];
    camera: Camera;
}

class Sphere implements Thing {

    radius2: number;

    constructor(public center: Vector, radius: number, public surface: Surface) {
        this.radius2 = radius * radius;
    }

    normal(pos: Vector): Vector {
        return Vector.norm(Vector.minus(pos, this.center));
    }

    intersect(ray: Ray) {
        var eo = Vector.minus(this.center, ray.start);
        var v = Vector.dot(eo, ray.dir);
        var dist = 0;
        if (v >= 0) {
            var disc = this.radius2 - (Vector.dot(eo, eo) - v * v);
            if (disc >= 0) {
                dist = v - Math.sqrt(disc);
            }
        }
        if (dist === 0) {
            return null;
        } else {
            return { thing: this, ray: ray, dist: dist };
        }
    }

}

class Plane implements Thing {

    normal: (pos: Vector) => Vector;
    intersect: (ray: Ray) => Intersection;

    constructor(norm: Vector, offset: number, public surface: Surface) {
        this.normal = function(pos: Vector) { return norm; }
        this.intersect = function(ray: Ray): Intersection {
            var denom = Vector.dot(norm, ray.dir);
            if (denom > 0) {
                return null;
            } else {
                var dist = (Vector.dot(norm, ray.start) + offset) / (-denom);
                return { thing: this, ray: ray, dist: dist };
            }
        }
    }

}

module Surfaces {

    export var shiny: Surface = {
        diffuse: function(pos) { return Color.white; },
        specular: function(pos) { return Color.grey; },
        reflect: function(pos) { return 0.7; },
        roughness: 250
    }

    export var checkerboard: Surface = {
        diffuse: function(pos) {
            if ((Math.floor(pos.z) + Math.floor(pos.x)) % 2 !== 0) {
                return Color.white;
            } else {
                return Color.black;
            }
        },
        specular: function(pos) { return Color.white; },
        reflect: function(pos) {
            if ((Math.floor(pos.z) + Math.floor(pos.x)) % 2 !== 0) {
                return 0.1;
            } else {
                return 0.7;
            }
        },
        roughness: 150
    }

}


class RayTracer {

    private maxDepth = 5;

    private intersections(ray: Ray, scene: Scene) {
        var closest = +Infinity;
        var closestInter: Intersection = undefined;
        for (var i in scene.things) {
            var inter = scene.things[i].intersect(ray);
            if (inter != null && inter.dist < closest) {
                closestInter = inter;
                closest = inter.dist;
            }
        }
        return closestInter;
    }

    private testRay(ray: Ray, scene: Scene) {
        var isect = this.intersections(ray, scene);
        if (isect != null) {
            return isect.dist;
        } else {
            return undefined;
        }
    }

    private traceRay(ray: Ray, scene: Scene, depth: number): Color {
        var isect = this.intersections(ray, scene);
        if (isect === undefined) {
            return Color.background;
        } else {
            return this.shade(isect, scene, depth);
        }
    }

    private shade(isect: Intersection, scene: Scene, depth: number) {
        var d = isect.ray.dir;
        var pos = Vector.plus(Vector.times(isect.dist, d), isect.ray.start);
        var normal = isect.thing.normal(pos);
        var reflectDir = Vector.minus(d, Vector.times(2, Vector.times(Vector.dot(normal, d), normal)));
        var naturalColor = Color.plus(Color.background,
                                      this.getNaturalColor(isect.thing, pos, normal, reflectDir, scene));
        var reflectedColor = (depth >= this.maxDepth) ? Color.grey : this.getReflectionColor(isect.thing, pos, normal, reflectDir, scene, depth);
        return Color.plus(naturalColor, reflectedColor);
    }

    private getReflectionColor(thing: Thing, pos: Vector, normal: Vector, rd: Vector, scene: Scene, depth: number) {
        return Color.scale(thing.surface.reflect(pos), this.traceRay({ start: pos, dir: rd }, scene, depth + 1));
    }

    private getNaturalColor(thing: Thing, pos: Vector, norm: Vector, rd: Vector, scene: Scene) {
        var addLight = (col, light) => {
            var ldis = Vector.minus(light.pos, pos);
            var livec = Vector.norm(ldis);
            var neatIsect = this.testRay({ start: pos, dir: livec }, scene);
            var isInShadow = (neatIsect === undefined) ? false : (neatIsect <= Vector.mag(ldis));
            if (isInShadow) {
                return col;
            } else {
                var illum = Vector.dot(livec, norm);
                var lcolor = (illum > 0) ? Color.scale(illum, light.color)
                                          : Color.defaultColor;
                var specular = Vector.dot(livec, Vector.norm(rd));
                var scolor = (specular > 0) ? Color.scale(Math.pow(specular, thing.surface.roughness), light.color)
                                          : Color.defaultColor;
                return Color.plus(col, Color.plus(Color.times(thing.surface.diffuse(pos), lcolor),
                                                  Color.times(thing.surface.specular(pos), scolor)));
            }
        }
        return scene.lights.reduce(addLight, Color.defaultColor);
    }

    render(scene, ctx, screenWidth, screenHeight) {
        var getPoint = (x, y, camera) => {
            var recenterX = x => (x - (screenWidth / 2.0)) / 2.0 / screenWidth;
            var recenterY = y => -(y - (screenHeight / 2.0)) / 2.0 / screenHeight;
            return Vector.norm(Vector.plus(camera.forward, Vector.plus(Vector.times(recenterX(x), camera.right), Vector.times(recenterY(y), camera.up))));
        }
        for (var y = 0; y < screenHeight; y++) {
            for (var x = 0; x < screenWidth; x++) {
                var color = this.traceRay({ start: scene.camera.pos, dir: getPoint(x, y, scene.camera) }, scene, 0);
                var c = Color.toDrawingColor(color);
                ctx.fillStyle = "rgb(" + String(c.r) + ", " + String(c.g) + ", " + String(c.b) + ")";
                ctx.fillRect(x, y, x + 1, y + 1);
            }
        }
    }

}


function defaultScene(): Scene {
    return {
        things: [new Plane(new Vector(0.0, 1.0, 0.0), 0.0, Surfaces.checkerboard),
                 new Sphere(new Vector(0.0, 1.0, -0.25), 1.0, Surfaces.shiny),
                 new Sphere(new Vector(-1.0, 0.5, 1.5), 0.5, Surfaces.shiny)],
        lights: [{ pos: new Vector(-2.0, 2.5, 0.0), color: new Color(0.49, 0.07, 0.07) },
                 { pos: new Vector(1.5, 2.5, 1.5), color: new Color(0.07, 0.07, 0.49) },
                 { pos: new Vector(1.5, 2.5, -1.5), color: new Color(0.07, 0.49, 0.071) },
                 { pos: new Vector(0.0, 3.5, 0.0), color: new Color(0.21, 0.21, 0.35) }],
        camera: new Camera(new Vector(3.0, 2.0, 4.0), new Vector(-1.0, 0.5, 0.0))
    };
}

function exec() {
    var canv = document.createElement("canvas");
    canv.width = 256;
    canv.height = 256;
    document.body.appendChild(canv);
    var ctx = canv.getContext("2d");
    var rayTracer = new RayTracer();
    return rayTracer.render(defaultScene(), ctx, 256, 256);
}

exec();