text:
// Muaz Khan     - https://github.com/muaz-khan
// MIT License   - https://www.webrtc-experiment.com/licence/
// Documentation - https://github.com/muaz-khan/WebRTC-Experiment/tree/master/DataChannel
// ==============
// DataChannel.js

(function() {
    window.DataChannel = function(channel, extras) {
        if (channel) this.automatic = true;
        this.channel = channel || location.href.replace( /\/|:|#|%|\.|\[|\]/g , '');

        extras = extras || { };

        var self = this,
            dataConnector, fileReceiver, textReceiver;

        this.onmessage = function(message, userid) {
            console.debug(userid, 'sent message:', message);
        };

        this.channels = { };
        this.onopen = function(userid) {
            console.debug(userid, 'is connected with you.');
        };

        this.onclose = function(event) {
            console.error('data channel closed:', event);
        };

        this.onerror = function(event) {
            console.error('data channel error:', event);
        };

        // by default; received file will be auto-saved to disk
        this.autoSaveToDisk = true;
        this.onFileReceived = function(fileName) {
            console.debug('File <', fileName, '> received successfully.');
        };

        this.onFileSent = function(file) {
            console.debug('File <', file.name, '> sent successfully.');
        };

        this.onFileProgress = function(packets) {
            console.debug('<', packets.remaining, '> items remaining.');
        };

        function prepareInit(callback) {
            for (var extra in extras) {
                self[extra] = extras[extra];
            }
            self.direction = self.direction || 'many-to-many';
            if (self.userid) window.userid = self.userid;

            if (!self.openSignalingChannel) {
                if (typeof self.transmitRoomOnce == 'undefined') self.transmitRoomOnce = true;

                // socket.io over node.js: https://github.com/muaz-khan/WebRTC-Experiment/blob/master/socketio-over-nodejs
                self.openSignalingChannel = function(config) {
                    config = config || { };

                    channel = config.channel || self.channel || 'default-channel';
                    var socket = new window.Firebase('https://' + (self.firebase || 'chat') + '.firebaseIO.com/' + channel);
                    socket.channel = channel;

                    socket.on('child_added', function(data) {
                        config.onmessage(data.val());
                    });

                    socket.send = function(data) {
                        this.push(data);
                    };

                    if (!self.socket) self.socket = socket;
                    if (channel != self.channel || (self.isInitiator && channel == self.channel))
                        socket.onDisconnect().remove();

                    if (config.onopen) setTimeout(config.onopen, 1);

                    return socket;
                };

                if (!window.Firebase) {
                    var script = document.createElement('script');
                    script.src = 'https://cdn.firebase.com/v0/firebase.js';
                    script.onload = callback;
                    document.documentElement.appendChild(script);
                } else callback();
            } else callback();
        }

        function init() {
            if (self.config) return;

            self.config = {
                ondatachannel: function(room) {
                    if (!dataConnector) {
                        self.room = room;
                        return;
                    }

                    var tempRoom = {
                        id: room.roomToken,
                        owner: room.broadcaster
                    };

                    if (self.ondatachannel) return self.ondatachannel(tempRoom);

                    if (self.joinedARoom) return;
                    self.joinedARoom = true;

                    self.join(tempRoom);
                },
                onopen: function(userid, _channel) {
                    self.onopen(userid, _channel);
                    self.channels[userid] = {
                        channel: _channel,
                        send: function(data) {
                            self.send(data, this.channel);
                        }
                    };
                },
                onmessage: function(data, userid) {
                    if (IsDataChannelSupported && !data.size) data = JSON.parse(data);

                    if (!IsDataChannelSupported) {
                        if (data.userid === window.userid) return;
                        data = data.message;
                    }

                    if (data.type === 'text')
                        textReceiver.receive(data, self.onmessage, userid);

                    else if (data.size || data.type === 'file')
                        fileReceiver.receive(data, self);

                    else self.onmessage(data, userid);
                },
                onclose: function(event) {
                    var myChannels = self.channels,
                        closedChannel = event.currentTarget;

                    for (var userid in myChannels) {
                        if (closedChannel === myChannels[userid].channel) {
                            delete myChannels[userid];
                        }
                    }

                    self.onclose(event);
                }
            };

            dataConnector = IsDataChannelSupported ?
                new DataConnector(self, self.config) :
                new SocketConnector(self.channel, self.config);

            fileReceiver = new FileReceiver();
            textReceiver = new TextReceiver();

            if (self.room) self.config.ondatachannel(self.room);
        }

        this.open = function(_channel) {
            self.joinedARoom = true;

            if (self.socket) self.socket.onDisconnect().remove();
            else self.isInitiator = true;

            if (_channel) self.channel = _channel;

            prepareInit(function() {
                init();
                if (IsDataChannelSupported) dataConnector.createRoom();
            });
        };

        this.connect = function(_channel) {
            if (_channel) self.channel = _channel;
            prepareInit(init);
        };

        // manually join a room
        this.join = function(room) {
            if (!room.id || !room.owner) {
                throw 'Invalid room info passed.';
            }

            dataConnector.joinRoom({
                roomToken: room.id,
                joinUser: room.owner
            });
        };

        this.send = function(data, _channel) {
            if (!data) throw 'No file, data or text message to share.';
            if (data.size)
                FileSender.send({
                    file: data,
                    channel: dataConnector,

                    onFileSent: function(file) {
                        self.onFileSent(file);
                    },
                    onFileProgress: function(packets, uuid) {
                        self.onFileProgress(packets, uuid);
                    },

                    _channel: _channel
                });
            else
                TextSender.send({
                    text: data,
                    channel: dataConnector,
                    _channel: _channel
                });
        };

        this.onleave = function(userid) {
            console.debug(userid, 'left!');
        };

        this.leave = this.eject = function(userid) {
            dataConnector.leave(userid, self.autoCloseEntireSession);
        };

        this.openNewSession = function(isOpenNewSession, isNonFirebaseClient) {
            if (isOpenNewSession) {
                if (self.isNewSessionOpened) return;
                self.isNewSessionOpened = true;

                if (!self.joinedARoom) self.open();
            }

            if (!isOpenNewSession || isNonFirebaseClient) self.connect();

            // for non-firebase clients
            if (isNonFirebaseClient)
                setTimeout(function() {
                    self.openNewSession(true);
                }, 5000);
        };

        if (self.automatic) {
            if (window.Firebase) {
                console.debug('checking presence of the room..');
                new window.Firebase('https://' + (extras.firebase || self.firebase || 'chat') + '.firebaseIO.com/' + self.channel).once('value', function(data) {
                    console.debug('room is present?', data.val() != null);
                    self.openNewSession(data.val() == null);
                });
            } else self.openNewSession(false, true);
        }
    };

    function DataConnector(root, config) {
        var self = { };
        var that = this;

        self.userToken = root.userid = root.userid || uniqueToken();
        self.sockets = [];
        self.socketObjects = { };

        var channels = '--',
            isbroadcaster, isGetNewRoom = true,
            RTCDataChannels = [];

        function newPrivateSocket(_config) {
            var socketConfig = {
                channel: _config.channel,
                onmessage: socketResponse,
                onopen: function() {
                    if (isofferer && !peer) initPeer();

                    _config.socketIndex = socket.index = self.sockets.length;
                    self.socketObjects[socketConfig.channel] = socket;
                    self.sockets[_config.socketIndex] = socket;
                }
            };

            socketConfig.callback = function(_socket) {
                socket = _socket;
                socketConfig.onopen();
            };

            var socket = root.openSignalingChannel(socketConfig),
                isofferer = _config.isofferer,
                gotstream, inner = { }, peer;

            var peerConfig = {
                onICE: function(candidate) {
                    socket && socket.send({
                        userToken: self.userToken,
                        candidate: {
                            sdpMLineIndex: candidate.sdpMLineIndex,
                            candidate: JSON.stringify(candidate.candidate)
                        }
                    });
                },
                onopen: onChannelOpened,
                onmessage: function(event) {
                    config.onmessage(event.data, _config.userid);
                },
                onclose: config.onclose,
                onerror: root.onerror
            };

            function initPeer(offerSDP) {
                if (root.direction === 'one-to-one' && window.isFirstConnectionOpened) return;

                if (!offerSDP) peerConfig.onOfferSDP = sendsdp;
                else {
                    peerConfig.offerSDP = offerSDP;
                    peerConfig.onAnswerSDP = sendsdp;
                }

                peer = RTCPeerConnection(peerConfig);
            }

            function onChannelOpened(channel) {
                channel.peer = peer.peer;
                RTCDataChannels.push(channel);

                config.onopen(_config.userid, channel);

                if (root.direction === 'many-to-many' && isbroadcaster && channels.split('--').length > 3) {
                    defaultSocket && defaultSocket.send({
                        newParticipant: socket.channel,
                        userToken: self.userToken
                    });
                }

                window.isFirstConnectionOpened = gotstream = true;
            }

            function sendsdp(sdp) {
                sdp = JSON.stringify(sdp);
                var part = parseInt(sdp.length / 3);

                var firstPart = sdp.slice(0, part),
                    secondPart = sdp.slice(part, sdp.length - 1),
                    thirdPart = '';

                if (sdp.length > part + part) {
                    secondPart = sdp.slice(part, part + part);
                    thirdPart = sdp.slice(part + part, sdp.length);
                }

                socket.send({
                    userToken: self.userToken,
                    firstPart: firstPart
                });

                socket.send({
                    userToken: self.userToken,
                    secondPart: secondPart
                });

                socket.send({
                    userToken: self.userToken,
                    thirdPart: thirdPart
                });
            }

            function socketResponse(response) {
                if (response.userToken == self.userToken) return;

                if (response.firstPart || response.secondPart || response.thirdPart) {
                    if (response.firstPart) {
                        // sdp sender's user id passed over "onopen" method
                        _config.userid = response.userToken;

                        inner.firstPart = response.firstPart;
                        if (inner.secondPart && inner.thirdPart) selfInvoker();
                    }
                    if (response.secondPart) {
                        inner.secondPart = response.secondPart;
                        if (inner.firstPart && inner.thirdPart) selfInvoker();
                    }

                    if (response.thirdPart) {
                        inner.thirdPart = response.thirdPart;
                        if (inner.firstPart && inner.secondPart) selfInvoker();
                    }
                }

                if (response.candidate && !gotstream) {
                    peer && peer.addICE({
                        sdpMLineIndex: response.candidate.sdpMLineIndex,
                        candidate: JSON.parse(response.candidate.candidate)
                    });

                    console.debug('ice candidate', response.candidate.candidate);
                }

                if (response.left) {
                    if (peer && peer.peer) {
                        peer.peer.close();
                        peer.peer = null;
                    }

                    if (response.closeEntireSession) leaveChannels();
                    else if (socket) {
                        socket.send({
                            left: true,
                            userToken: self.userToken
                        });
                        socket = null;
                    }

                    root.onleave(response.userToken);
                }

                if (response.playRoleOfBroadcaster)
                    setTimeout(function() {
                        self.roomToken = response.roomToken;
                        root.open(self.roomToken);
                        self.sockets = swap(self.sockets);
                    }, 600);
            }

            var invokedOnce = false;

            function selfInvoker() {
                if (invokedOnce) return;

                invokedOnce = true;
                inner.sdp = JSON.parse(inner.firstPart + inner.secondPart + inner.thirdPart);

                if (isofferer) peer.addAnswerSDP(inner.sdp);
                else initPeer(inner.sdp);

                console.debug('sdp', inner.sdp.sdp);
            }
        }

        function onNewParticipant(channel) {
            if (!channel || channels.indexOf(channel) != -1 || channel == self.userToken) return;
            channels += channel + '--';

            var new_channel = uniqueToken();

            newPrivateSocket({
                channel: new_channel,
                closeSocket: true
            });

            defaultSocket.send({
                participant: true,
                userToken: self.userToken,
                joinUser: channel,
                channel: new_channel
            });
        }

        function uniqueToken() {
            return Math.round(Math.random() * 60535) + 5000000;
        }

        function leaveChannels(channel) {
            var alert = {
                left: true,
                userToken: self.userToken
            };

            // if room initiator is leaving the room; close the entire session
            if (isbroadcaster) {
                if (root.autoCloseEntireSession) alert.closeEntireSession = true;
                else
                    self.sockets[0].send({
                        playRoleOfBroadcaster: true,
                        userToken: self.userToken,
                        roomToken: self.roomToken
                    });
            }

            if (!channel) {
                // closing all sockets
                var sockets = self.sockets,
                    length = sockets.length;

                for (var i = 0; i < length; i++) {
                    var socket = sockets[i];
                    if (socket) {
                        socket.send(alert);

                        if (self.socketObjects[socket.channel])
                            delete self.socketObjects[socket.channel];

                        delete sockets[i];
                    }
                }

                that.left = true;
            }

            // eject a specific user!
            if (channel) {
                socket = self.socketObjects[channel];
                if (socket) {
                    socket.send(alert);

                    if (self.sockets[socket.index])
                        delete self.sockets[socket.index];

                    delete self.socketObjects[channel];
                }
            }
            self.sockets = swap(self.sockets);
        }

        window.onbeforeunload = function() {
            leaveChannels();
        };

        window.onkeyup = function(e) {
            if (e.keyCode == 116) leaveChannels();
        };

        (function() {
            var anchors = document.querySelectorAll('a'),
                length = anchors.length;
            for (var i = 0; i < length; i++) {
                var a = anchors[i];
                if (a.href.indexOf('#') !== 0 && a.getAttribute('target') != '_blank')
                    a.onclick = function() {
                        leaveChannels();
                    };
            }
        })();

        var defaultSocket = root.openSignalingChannel({
            onmessage: function(response) {
                if (response.userToken == self.userToken) return;

                if (isGetNewRoom && response.roomToken && response.broadcaster) config.ondatachannel(response);

                if (response.newParticipant) onNewParticipant(response.newParticipant);

                if (response.userToken && response.joinUser == self.userToken && response.participant && channels.indexOf(response.userToken) == -1) {
                    channels += response.userToken + '--';

                    console.debug('Data connection is being opened between you and', response.userToken || response.channel);
                    newPrivateSocket({
                        isofferer: true,
                        channel: response.channel || response.userToken,
                        closeSocket: true
                    });
                }
            },
            callback: function(socket) {
                defaultSocket = socket;
            }
        });

        return {
            createRoom: function() {
                self.roomToken = uniqueToken();

                isbroadcaster = true;
                isGetNewRoom = false;

                (function transmit() {
                    defaultSocket && defaultSocket.send({
                        roomToken: self.roomToken,
                        broadcaster: self.userToken
                    });

                    if (!root.transmitRoomOnce && !that.leaving) {
                        if (root.direction === 'one-to-one') {
                            if (!window.isFirstConnectionOpened) setTimeout(transmit, 3000);
                        } else setTimeout(transmit, 3000);
                    }
                })();
            },
            joinRoom: function(_config) {
                self.roomToken = _config.roomToken;
                isGetNewRoom = false;

                newPrivateSocket({
                    channel: self.userToken
                });

                defaultSocket.send({
                    participant: true,
                    userToken: self.userToken,
                    joinUser: _config.joinUser
                });
            },
            send: function(message, _channel) {
                var _channels = RTCDataChannels,
                    data, length = _channels.length;
                if (!length) return;

                if (moz && message.file) data = message.file;
                else data = JSON.stringify(message);

                if (_channel) _channel.send(data);
                else
                    for (var i = 0; i < length; i++) _channels[i].send(data);
            },
            leave: function(userid, autoCloseEntireSession) {
                if (autoCloseEntireSession) root.autoCloseEntireSession = true;
                leaveChannels(userid);
                if (!userid) {
                    self.joinedARoom = isbroadcaster = false;
                    isGetNewRoom = true;
                }
            }
        };
    }

    function SocketConnector(_channel, config) {
        var channel = config.openSocket({
            channel: _channel,
            onopen: config.onopen,
            onmessage: config.onmessage
        });

        return {
            send: function(message) {
                channel && channel.send({
                    userid: userid,
                    message: message
                });
            }
        };
    }

    function getRandomString() {
        return (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace( /\./g , '-');
    }

    window.userid = getRandomString();

    var FileSender = {
        send: function(config) {
            var channel = config.channel,
                _channel = config._channel,
                file = config.file;

            var packetSize = 1000,
                textToTransfer = '',
                numberOfPackets = 0,
                packets = 0;

            // uuid is used to uniquely identify sending instance
            file.uuid = getRandomString();

            var reader = new window.FileReader();
            reader.readAsDataURL(file);
            reader.onload = onReadAsDataURL;

            function onReadAsDataURL(event, text) {
                var data = {
                    type: 'file',
                    uuid: file.uuid
                };

                if (event) {
                    text = event.target.result;
                    numberOfPackets = packets = data.packets = parseInt(text.length / packetSize);
                }

                if (config.onFileProgress)
                    config.onFileProgress({
                        remaining: packets--,
                        length: numberOfPackets,
                        sent: numberOfPackets - packets
                    }, file.uuid);

                if (text.length > packetSize) data.message = text.slice(0, packetSize);
                else {
                    data.message = text;
                    data.last = true;
                    data.name = file.name;

                    if (config.onFileSent) config.onFileSent(file, file.uuid);
                }

                // WebRTC-DataChannels.send(data, privateDataChannel)
                channel.send(data, _channel);

                textToTransfer = text.slice(data.message.length);

                if (textToTransfer.length) {
                    setTimeout(function() {
                        onReadAsDataURL(null, textToTransfer);
                    }, moz ? 1 : 500);
                    // bug: what's the best method to speedup data transferring on chrome?
                }
            }
        }
    };

    function FileReceiver() {
        var content = { },
            packets = { },
            numberOfPackets = { };

        // "root" is RTCMultiConnection object
        // "data" is object passed using WebRTC DataChannels

        function receive(data, root) {
            // uuid is used to uniquely identify sending instance
            var uuid = data.uuid;

            if (data.packets) numberOfPackets[uuid] = packets[uuid] = parseInt(data.packets);

            if (root.onFileProgress)
                root.onFileProgress({
                    remaining: packets[uuid]--,
                    length: numberOfPackets[uuid],
                    received: numberOfPackets[uuid] - packets[uuid]
                }, uuid);

            if (!content[uuid]) content[uuid] = [];

            content[uuid].push(data.message);

            // if it is last packet
            if (data.last) {
                var dataURL = content[uuid].join('');
                var blob = FileConverter.DataUrlToBlob(dataURL);
                var virtualURL = (window.URL || window.webkitURL).createObjectURL(blob);

                // if you don't want to auto-save to disk:
                // channel.autoSaveToDisk=false;
                if (root.autoSaveToDisk)
                    FileSaver.SaveToDisk(dataURL, data.name);

                // channel.onFileReceived = function(fileName, file) {}
                // file.blob || file.dataURL || file.url || file.uuid
                if (root.onFileReceived)
                    root.onFileReceived(data.name, {
                        blob: blob,
                        dataURL: dataURL,
                        url: virtualURL,
                        uuid: uuid
                    });
                delete content[uuid];
            }
        }

        return {
            receive: receive
        };
    }

    var FileSaver = {
        SaveToDisk: function(fileUrl, fileName) {
            var hyperlink = document.createElement('a');
            hyperlink.href = fileUrl;
            hyperlink.target = '_blank';
            hyperlink.download = fileName || fileUrl;

            var mouseEvent = new MouseEvent('click', {
                view: window,
                bubbles: true,
                cancelable: true
            });

            hyperlink.dispatchEvent(mouseEvent);
            (window.URL || window.webkitURL).revokeObjectURL(hyperlink.href);
        }
    };

    var FileConverter = {
        DataUrlToBlob: function(dataURL) {
            var binary = atob(dataURL.substr(dataURL.indexOf(',') + 1));
            var array = [];
            for (var i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }

            var type;

            try {
                type = dataURL.substr(dataURL.indexOf(':') + 1).split(';')[0];
            } catch(e) {
                type = 'text/plain';
            }

            return new Blob([new Uint8Array(array)], { type: type });
        }
    };

    var TextSender = {
        send: function(config) {
            var channel = config.channel,
                _channel = config._channel,
                initialText = config.text,
                packetSize = 1000 /* chars */,
                textToTransfer = '',
                isobject = false;

            if (typeof initialText !== 'string') {
                isobject = true;
                initialText = JSON.stringify(initialText);
            }

            // uuid is used to uniquely identify sending instance
            var uuid = getRandomString();
            var sendingTime = new Date().getTime();

            sendText(initialText);

            function sendText(textMessage, text) {
                var data = {
                    type: 'text',
                    uuid: uuid,
                    sendingTime: sendingTime
                };

                if (textMessage) {
                    text = textMessage;
                    data.packets = parseInt(text.length / packetSize);
                }

                if (text.length > packetSize)
                    data.message = text.slice(0, packetSize);
                else {
                    data.message = text;
                    data.last = true;
                    data.isobject = isobject;
                }

                channel.send(data, _channel);

                textToTransfer = text.slice(data.message.length);

                if (textToTransfer.length)
                    setTimeout(function() {
                        sendText(null, textToTransfer);
                    }, moz ? 1 : 500);
            }
        }
    };

    function TextReceiver() {
        var content = { };

        function receive(data, onmessage, userid) {
            // uuid is used to uniquely identify sending instance
            var uuid = data.uuid;
            if (!content[uuid]) content[uuid] = [];

            content[uuid].push(data.message);
            if (data.last) {
                var message = content[uuid].join('');
                if (data.isobject) message = JSON.parse(message);

                // bug: latency detection must be fixed
                // https://github.com/muaz-khan/WebRTC-Experiment/issues/63#issuecomment-21083575
                var receivingTime = new Date().getTime();
                var latency = Math.abs(receivingTime - data.sendingTime);

                if (onmessage) onmessage(message, userid, latency);

                delete content[uuid];
            }
        }

        return {
            receive: receive
        };
    }

    function swap(arr) {
        var swapped = [],
            length = arr.length;
        for (var i = 0; i < length; i++)
            if (arr[i]) swapped.push(arr[i]);
        return swapped;
    }

    window.moz = !!navigator.mozGetUserMedia;
    window.IsDataChannelSupported = !((moz && !navigator.mozGetUserMedia) || (!moz && !navigator.webkitGetUserMedia));

    function RTCPeerConnection(options) {
        var w = window,
            PeerConnection = w.mozRTCPeerConnection || w.webkitRTCPeerConnection,
            SessionDescription = w.mozRTCSessionDescription || w.RTCSessionDescription,
            IceCandidate = w.mozRTCIceCandidate || w.RTCIceCandidate;

        var STUN = {
            url: !moz ? 'stun:stun.l.google.com:19302' : 'stun:23.21.150.121'
        };

        var TURN = {
            url: 'turn:homeo@turn.bistri.com:80',
            credential: 'homeo'
        };

        var iceServers = {
            iceServers: options.iceServers || [STUN]
        };

        if (!moz && !options.iceServers) {
            if (parseInt(navigator.userAgent.match( /Chrom(e|ium)\/([0-9]+)\./ )[2]) >= 28)
                TURN = {
                    url: 'turn:turn.bistri.com:80',
                    credential: 'homeo',
                    username: 'homeo'
                };
            iceServers.iceServers = [STUN, TURN];
        }

        var optional = {
            optional: []
        };

        if (!moz) {
            optional.optional = [{
                RtpDataChannels: true
            }];
        }

        if (!navigator.onLine) {
            iceServers = null;
            console.warn('No internet connection detected. No STUN/TURN server is used to make sure local/host candidates are used for peers connection.');
        }

        var peerConnection = new PeerConnection(iceServers, optional);

        openOffererChannel();
        peerConnection.onicecandidate = onicecandidate;

        function onicecandidate(event) {
            if (!event.candidate || !peerConnection) return;
            if (options.onICE) options.onICE(event.candidate);
        }

        var constraints = options.constraints || {
            optional: [],
            mandatory: {
                OfferToReceiveAudio: !!moz,
                OfferToReceiveVideo: !!moz
            }
        };

		function onSdpError(e) {
            console.error('sdp error:', e.name, e.message);
        }

		function onSdpSuccess() {}

        function createOffer() {
            if (!options.onOfferSDP) return;

            peerConnection.createOffer(function(sessionDescription) {
                sessionDescription.sdp = setBandwidth(sessionDescription.sdp);
                peerConnection.setLocalDescription(sessionDescription);
                options.onOfferSDP(sessionDescription);
            }, onSdpError, constraints);
        }

        function createAnswer() {
            if (!options.onAnswerSDP) return;

            options.offerSDP = new SessionDescription(options.offerSDP);
            peerConnection.setRemoteDescription(options.offerSDP, onSdpSuccess, onSdpError);

            peerConnection.createAnswer(function(sessionDescription) {
                sessionDescription.sdp = setBandwidth(sessionDescription.sdp);
                peerConnection.setLocalDescription(sessionDescription);
                options.onAnswerSDP(sessionDescription);
            }, onSdpError, constraints);
        }

        function setBandwidth(sdp) {
            // Firefox has no support of "b=AS"
            if (moz) return sdp;

            // remove existing bandwidth lines
            sdp = sdp.replace( /b=AS([^\r\n]+\r\n)/g , '');
            sdp = sdp.replace( /a=mid:data\r\n/g , 'a=mid:data\r\nb=AS:1638400\r\n');

            return sdp;
        }

        if (!moz) {
            createOffer();
            createAnswer();
        }

        var channel;

        function openOffererChannel() {
            if (moz && !options.onOfferSDP) return;

            _openOffererChannel();
            if (moz) {
                navigator.mozGetUserMedia({
                        audio: true,
                        fake: true
                    }, function(stream) {
                        peerConnection.addStream(stream);
                        createOffer();
                    }, useless);
            }
        }

        function _openOffererChannel() {
            channel = peerConnection.createDataChannel(
                options.channel || 'RTCDataChannel',
                moz ? { } : {
                    reliable: false
                });
            if (moz) channel.binaryType = 'blob';
            setChannelEvents();
        }

        function setChannelEvents() {
            channel.onmessage = options.onmessage;
            channel.onopen = function() {
                options.onopen(channel);
            };
            channel.onclose = options.onclose;
            channel.onerror = options.onerror;
        }

        if (options.onAnswerSDP && moz && options.onmessage) openAnswererChannel();

        function openAnswererChannel() {
            peerConnection.ondatachannel = function(event) {
                channel = event.channel;
                channel.binaryType = 'blob';
                setChannelEvents();
            };

            if (moz) {
                navigator.mozGetUserMedia({
                        audio: true,
                        fake: true
                    }, function(stream) {
                        peerConnection.addStream(stream);
                        createAnswer();
                    }, useless);
            }
        }

        function useless() {}

        return {
            addAnswerSDP: function(sdp) {
                sdp = new SessionDescription(sdp);
                peerConnection.setRemoteDescription(sdp, onSdpSuccess, onSdpError);
            },
            addICE: function(candidate) {
                peerConnection.addIceCandidate(new IceCandidate({
                    sdpMLineIndex: candidate.sdpMLineIndex,
                    candidate: candidate.candidate
                }));
            },

            peer: peerConnection,
            channel: channel,
            sendData: function(message) {
                channel && channel.send(message);
            }
        };
    }
})();


text:
layout: post
title: Inicio de clases
subtitle: Inicio de clases
bigimg: /img/path.jpg
tags: [noticias 2020-1C]
---

Dado el contexto en que nos encontramos, en la materia decidimos habilitar el formulario de inscripción a la materia para que puedan ir registrándose. Tambien les dejo el link al canal de Slack del curso para tener la posibilidad de comenzar la cursada en forma virtual.
En caso de tener algún conocido/a que curse la materia este cuatrimestre les pido que le compartan este mensaje.

- Link formulario [`https://docs.google.com/forms/d/e/1FAIpQLSfdHoNCpal5_8T4sNFcdDkhESdR_LyGAzS0YXq6WEna9xWr4A/viewform?usp=send_form`](https://docs.google.com/forms/d/e/1FAIpQLSfdHoNCpal5_8T4sNFcdDkhESdR_LyGAzS0YXq6WEna9xWr4A/viewform?usp=send_form)
- Link Slack [`https://join.slack.com/t/7552-tallerii/shared_invite/zt-ctrqh1hu-Cb1VtoWeuzQzIPTEnLhN3w`](https://join.slack.com/t/7552-tallerii/shared_invite/zt-ctrqh1hu-Cb1VtoWeuzQzIPTEnLhN3w)

Muchas gracias,
Saludos

redpajama_set_name: RedPajamaGithub


text:
<form class="col-md-8 container" (ngSubmit)="onSubmit(form)" #form="ngForm">

        NOWY WYNIK GRY

        Gra

 0">
                <select class="form-control" [(ngModel)]="selectedBoardGame" #boardGameCtrl="ngModel" name="boardGame" required>
                    <option *ngFor="let boardGame of availableBoardGames"
                            [ngValue]="boardGame">
                        {{boardGame.Name}}
                    </option>
                </select>

                    Wybierz grę!

                Brak dostępnych gier

        Gracz

 0">
                <select class="form-control" [(ngModel)]="selectedGamer" #gamerCtrl="ngModel" name="gamer" required>
                    <option *ngFor="let gamer of availableGamers"
                            [ngValue]="gamer" >
                        {{gamer.Nickname}}
                    </option>
                </select>

                    Wybierz gracza!

                Brak dostępnych graczy

        Punkty

            <input class="form-control" type="number" id="points" name="points"
                   [(ngModel)]="points" #pointsCtrl="ngModel" required/>

                Podaj liczbę punktów!

        Miejsce

            <input class="form-control" type="number" id="place" name="place"
                   [(ngModel)]="place" #placeCtrl="ngModel" required/>

                Podaj miejsce!

        Liczba graczy

            <input class="form-control" type="number" id="playersNumber" name="playersNumber"
                   [(ngModel)]="playersNumber" #playersNumberCtrl="ngModel" required/>

                Podaj miejsce!

        <button type="button" class="btn btn-default" (click)="goBack()">
            Powrót
        </button>
        <button class="btn btn-success" type="submit" [disabled]="form.invalid">
            Dodaj
        </button>

</form>


text:
using System;
using System.Collections.Generic;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Infrastructure.Services;
using EspaceClient.BackOffice.Silverlight.Infrastructure.ServiceZonePage;
using EspaceClient.FrontOffice.Domaine;
using nRoute.Components.Composition;

namespace EspaceClient.BackOffice.Silverlight.Data.Depots
{
    /// <summary>
    /// Dépôt des zones de page.
    /// </summary>
    [MapResource(typeof(IDepotZonePage), InstanceLifetime.Singleton)]
    public class DepotZonePage : IDepotZonePage
    {
        private readonly IServiceClientFactory _services;
        private readonly IApplicationContext _applicationContext;

        /// <summary>
        /// Initialise une nouvelle instance du dépôt.
        /// </summary>
        /// <param name="services">Fournisseur de services.</param>
        /// <param name="scheduler">Scheduler de tâches.</param>
        [ResolveConstructor]
        public DepotZonePage(IApplicationContext applicationContext, IServiceClientFactory services)
        {
            _applicationContext = applicationContext;
            _services = services;
        }

        /// <summary>
        /// Récupère la liste des zones de page.
        /// </summary>
        /// <param name="appContext">Context de l'application courante.</param>
        /// <param name="callback">Méthode éxécutée à la fin du traitement.</param>
        public void GetAll(Action<IEnumerable<ZonePageDto>> callback, Action<Exception> error)
        {
            _services.ServiceZonePage.Call<GetAllCompletedEventArgs>(
                s => s.GetAllAsync(_applicationContext.Context),
                r =>
                {
                    if (r.Error != null)
                        error(r.Error);
                    else
                        callback(r.Result);

                });
        }
    }
}


text:
\section{Namespace List}
Here is a list of all namespaces with brief descriptions\-:\begin{DoxyCompactList}
\item\contentsline{section}{\hyperlink{namespace_noesis}{Noesis} }{\pageref{namespace_noesis}}{}
\item\contentsline{section}{\hyperlink{namespace_noesis_1_1_gui}{Noesis\-::\-Gui} }{\pageref{namespace_noesis_1_1_gui}}{}
\end{DoxyCompactList}


text:
<?php

namespace Solution\JsonRpcApiExtension\Context;

use Behat\Behat\Context\Context;
use Graze\GuzzleHttp\JsonRpc\ClientInterface;

interface JsonRpcClientAwareContext extends Context
{
    /**
     * Sets Json-Rpc Client instance.
     *
     * @param ClientInterface $client
     * @return void
     */
    public function setClient(ClientInterface $client);
}


text:
import React, { Component } from 'react'
import { api } from '../utils/api'
import { ContainerFull, GlobalDiv } from '../styles/globals'

export class Home extends Component {
    constructor(props) {
        super(props)
    }

    componentWillMount() {
        const { search } = this.props.location
        if (search && search !== "") {
            if (search.split('=')[0].split('?')[1] === 'delogged') {
                localStorage.setItem('logged', 'false')
                localStorage.removeItem('user')
                return api.getToken()
            }
            const params = search.split('=')
            const token = search.split('=')[1].split('&')[0]
            localStorage.setItem('token', `bearer ${token}`)
            localStorage.setItem('user', params[2])
            localStorage.setItem('logged', 'true')

        }
    }

    render() {
        return (
            <GlobalDiv>
                <ContainerFull>

Fancy Git

Welcome on Fancy Git, you can access all repos, all user from GitHub when you want.

                        When logged you can mark repos to keep them in your profile.

                </ContainerFull>
            </GlobalDiv>
        )
    }
}


text:
"""Neural network module."""

from .parameter import *

from .block import *

from . import nn

from . import rnn

from .trainer import *

from . import loss

from . import utils

from . import data


text:
'use strict'

var PropTypes = require('prop-types')

var React = require('react')
var createReactClass = require('create-react-class')
var ReactBootstrap = require('react-bootstrap')
var Label = ReactBootstrap.Label

var Tag = createReactClass({
  displayName: 'Tag',

  propTypes: {
    tagName: PropTypes.string.isRequired
  },

  render: function () {
    return {this.props.tagName}
  }
})

var TagList = createReactClass({
  displayName: 'TagList',

  propTypes: {
    tags: PropTypes.array.isRequired
  },

  render: function () {
    return (

        {this.props.tags.map(function (tag, i) {
          return <Tag key={tag.id} tagName={tag.name} />
        })}

    )
  }
})

module.exports = TagList


text:
import sys

PY3 = sys.version_info[0] >= 3

if PY3:
    basestring = str
    unicode_type = str
    bytes_type = bytes

    def iteritems(d):
        return iter(d.items())

    def itervalues(d):
        return iter(d.values())
    pyrange = range
    pyzip = zip
    pylong = int
    from configparser import SafeConfigParser
else:
    # Python 2
    basestring = basestring
    unicode_type = unicode
    bytes_type = str

    def iteritems(d):
        return d.iteritems()

    def itervalues(d):
        return d.itervalues()
    pyrange = xrange
    from itertools import izip as pyzip
    pylong = long
    from ConfigParser import SafeConfigParser
try:
    from cyordereddict import OrderedDict
except ImportError:
    try:
        from collections import OrderedDict
    except ImportError:
        from ordereddict import OrderedDict


text:
package try_ddd.try_ddd.domain.comic;

import java.util.Date;

import try_ddd.try_ddd.domain.comic.Copy.States;

public class Borrow {
	private Date startDate;
	private Date endDate;
	private Copy copy;
	private Friend friend;

	private Date givenBackDate = null;

	private States givenBackInState = null;

	public Borrow(Date startDate, Date endDate, Copy copy, Friend friend) {
		this.startDate = startDate;
		this.endDate = endDate;
		this.copy = copy;
		this.friend = friend;

	}

	public Date getStartDate() {
		return startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public Copy getCopy() {
		return copy;
	}

	public Date getGivenBackDate() {
		return givenBackDate;
	}

	public void setGivenBackDate(Date givenBackDate) {
		this.givenBackDate = givenBackDate;
	}

	public States getGivenBackInState() {
		return givenBackInState;
	}

	public void setGivenBackInState(States givenBackInState) {
		this.givenBackInState = givenBackInState;
	}

	public Friend getFriend(){
		return this.friend;
	}

}


text:
@interface SFSwitchTabController () <UIScrollViewDelegate>

@property (nonatomic, weak) UIScrollView *scrollView;
@property (nonatomic, assign) CGFloat scrollViewLastContentOffsetX;
@property (nonatomic, assign) BOOL scrollViewDragging;
@property (nonatomic, assign) BOOL scrollViewAnimating;
@property (nonatomic, strong) UIViewController *lastDisplayViewController;
@property (nonatomic, strong) UIViewController *nextDisplayViewController;

@property (nonatomic, assign) BOOL firstAppeared;

@property (nonatomic, copy) void(^scrollAnimationCompletion)(void);

@end

@implementation SFSwitchTabController

- (id)init {
    self = [super init];

    self.selectedIndex = -1;

    return self;
}

- (void)loadView {
    [super loadView];
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.pagingEnabled = YES;
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    scrollView.delegate = self;
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.scrollsToTop = NO;
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;

    __weak typeof(self) weakSelf = self;
    [SFTrackProperty(self.view, frame) onChange:^(id value) {
        __strong typeof(weakSelf) self = weakSelf;
        self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width * self.viewControllers.count, self.view.frame.size.height);
    }];

    [SFTrackProperty(self, scrollable) onChange:^(id value) {
        __strong typeof(weakSelf) self = weakSelf;
        self.scrollView.scrollEnabled = self.scrollable;
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!self.firstAppeared) {
        self.firstAppeared = YES;
        if (self.selectedIndex == -1) {
            [self _addChildViewControllerIfNeededWithIndex:0 outAdded:NULL];
            self.selectedIndex = 0;
        } else {
            [self _addChildViewControllerIfNeededWithIndex:self.selectedIndex outAdded:NULL];
        }
    }
}

- (UIViewController *)selectedViewController {
    if (_selectedIndex == -1) {
        return nil;
    }

    return [_viewControllers objectAtIndex:_selectedIndex];
}

- (void)setViewControllers:(NSArray *)viewControllers {
    if ([_viewControllers count] != 0) {
        [_viewControllers enumerateObjectsUsingBlock:^(UIViewController *obj, NSUInteger idx, BOOL *stop) {
            [obj willMoveToParentViewController:nil];
            if ([obj isViewLoaded] && obj.view.superview == self.scrollView) {
                [obj.view removeFromSuperview];
            }
            [obj removeFromParentViewController];
        }];
    }
    _viewControllers = viewControllers;

    _scrollView.contentSize = CGSizeMake(self.view.frame.size.width * _viewControllers.count, self.view.frame.size.height);

    [self scrollViewDidScroll:_scrollView];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return [self.selectedViewController preferredStatusBarStyle];
}

- (BOOL)prefersStatusBarHidden {
    return [self.selectedViewController prefersStatusBarHidden];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    [self setSelectedIndex:selectedIndex animated:NO];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex animated:(BOOL)animated {
    [self setSelectedIndex:selectedIndex animated:animated completion:nil];
}

- (void)setSelectedIndex:(NSInteger)selectedIndex animated:(BOOL)animated completion:(void(^)(void))completion {
    if (selectedIndex != _selectedIndex) {
        if (!animated) {
            _selectedIndex = selectedIndex;
        }
        self.scrollViewAnimating = animated;
        [self.scrollView scrollRectToVisible:CGRectMake(selectedIndex * _scrollView.frame.size.width, 0, _scrollView.frame.size.width, _scrollView.frame.size.height) animated:animated];
        self.scrollAnimationCompletion = completion;
        self.scrollViewLastContentOffsetX = selectedIndex * _scrollView.frame.size.width;
    }
}

- (UIViewController *)_addChildViewControllerIfNeededWithIndex:(NSInteger)index outAdded:(BOOL *)outAdded {
    UIViewController *nextViewController = nil;
    if (index < _viewControllers.count) {
        UIViewController *viewController = [_viewControllers objectAtIndex:index];
        if (viewController.parentViewController != self) {
            [self addChildViewController:viewController];
            [self.scrollView addSubview:viewController.view];
            viewController.view.frame = CGRectMake(index * _scrollView.frame.size.width, 0, _scrollView.frame.size.width, _scrollView.frame.size.height);
            [viewController didMoveToParentViewController:self];
            if (outAdded != NULL) {
                *outAdded = YES;
            }
        } else {
            viewController.view.frame = CGRectMake(index * _scrollView.frame.size.width, 0, _scrollView.frame.size.width, _scrollView.frame.size.height);
        }
        nextViewController = viewController;
    }

    return nextViewController;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.scrollAnimationCompletion = nil;

    self.scrollViewDragging = YES;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    self.scrollViewDragging = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self _scrollViewDidStatic];
}

- (void)_scrollViewDidStatic {
    NSInteger scrollViewControllerIndex = self.scrollView.contentOffset.x / self.scrollView.frame.size.width;
    if (scrollViewControllerIndex != _selectedIndex) {
        if (_nextDisplayViewController) {
            if (self.selectedViewController != self.nextDisplayViewController) {
                [self.selectedViewController willMoveToParentViewController:nil];
                [self.selectedViewController.view removeFromSuperview];
                [self.selectedViewController removeFromParentViewController];
            }
            for (NSInteger i = 0; i < self.viewControllers.count; ++i) {
                if (i != self.selectedIndex && i != scrollViewControllerIndex) {
                    UIViewController *viewController = [self.viewControllers objectAtIndex:i];
                    [viewController willMoveToParentViewController:nil];
                    [viewController.view removeFromSuperview];
                    [viewController removeFromParentViewController];
                }
            }
            [self.selectedViewController endAppearanceTransition];
        }
        [self willChangeValueForKey:@"selectedIndex"];
        _selectedIndex = scrollViewControllerIndex;
        [self didChangeValueForKey:@"selectedIndex"];
        if ([_delegate respondsToSelector:@selector(switchTabController:didSwitchToIndex:)]) {
            [_delegate switchTabController:self didSwitchToIndex:_selectedIndex];
        }
    } else {
        if (_nextDisplayViewController && self.nextDisplayViewController != self.selectedViewController) {
            [self.selectedViewController beginAppearanceTransition:YES animated:NO];
            [self.nextDisplayViewController beginAppearanceTransition:NO animated:NO];

            [self.nextDisplayViewController willMoveToParentViewController:nil];
            [self.nextDisplayViewController.view removeFromSuperview];
            [self.nextDisplayViewController removeFromParentViewController];

            [self.nextDisplayViewController endAppearanceTransition];
            [self.selectedViewController endAppearanceTransition];
        }
    }
    self.nextDisplayViewController = nil;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self _scrollViewDidStatic];
    if (self.scrollAnimationCompletion) {
        self.scrollAnimationCompletion();
        self.scrollAnimationCompletion = nil;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat x = scrollView.contentOffset.x;
    BOOL toRight = x - _scrollViewLastContentOffsetX > 0;
    self.scrollViewLastContentOffsetX = x;
    NSInteger scrollViewControllerIndex = 0;
    if (toRight) {
        scrollViewControllerIndex = (x + scrollView.frame.size.width + (_scrollViewDragging ? 0.50f : -.50f)) / scrollView.frame.size.width;
    } else {
        scrollViewControllerIndex = (x - (_scrollViewDragging ? 0.50f : 0)) / scrollView.frame.size.width;
    }
    BOOL outAdded = NO;
    UIViewController *nextViewController = [self _addChildViewControllerIfNeededWithIndex:scrollViewControllerIndex outAdded:&outAdded];
    if (nextViewController != nil && nextViewController != [self selectedViewController] && nextViewController != _nextDisplayViewController) {
        self.nextDisplayViewController = nextViewController;

        if (!outAdded) {
            [self.nextDisplayViewController beginAppearanceTransition:YES animated:self.scrollViewAnimating];
        }

        [self.selectedViewController beginAppearanceTransition:NO animated:self.scrollViewAnimating];

        if ([_delegate respondsToSelector:@selector(switchTabController:willSwitchToIndex:)]) {
            [_delegate switchTabController:self willSwitchToIndex:scrollViewControllerIndex];
        }
    }
}

@end


text:
export default function openImage(canvas) {
    const {width, height} = canvas;
    const win = window.open('', 'image');
    const src = canvas.toDataURL('image/png');
    win.document.write(`<img src="${src}" width="${width}" height="${height}">`);
}


text:
DOTFILES=$HOME/.dotfiles

echo -e "\nCreating symlinks"
echo "=============================="
linkables=$( find -H "$DOTFILES" -maxdepth 3 -name '*.symlink' )
for file in $linkables ; do
    target="$HOME/.$( basename $file '.symlink' )"
    if [ -e $target ]; then
        echo "~${target#$HOME} already exists... Skipping."
    else
        echo "Creating symlink for $file"
        ln -s $file $target
    fi
done

echo -e "\n\ninstalling to ~/.config"
echo "=============================="
if [ ! -d $HOME/.config ]; then
    echo "Creating ~/.config"
    mkdir -p $HOME/.config
fi

for config in $DOTFILES/config/*; do
    target=$HOME/.config/$( basename $config )
    if [ -e $target ]; then
        echo "~${target#$HOME} already exists... Skipping."
    else
        echo "Creating symlink for $config"
        ln -s $config $target
    fi
done

# create vim symlinks
# As I have moved off of vim as my full time editor in favor of neovim,
# I feel it doesn't make sense to leave my vimrc intact in the dotfiles repo
# as it is not really being actively maintained. However, I would still
# like to configure vim, so lets symlink ~/.vimrc and ~/.vim over to their
# neovim equivalent.

echo -e "\n\nCreating vim symlinks"
echo "=============================="
VIMFILES=( "$HOME/.vim:$DOTFILES/vim/.vim"
        "$HOME/.vimrc:$DOTFILES/vim/.vimrc" )

for file in "${VIMFILES[@]}"; do
    KEY=${file%%:*}
    VALUE=${file#*:}
    if [ -e ${KEY} ]; then
        echo "${KEY} already exists... skipping."
    else
        echo "Creating symlink for $KEY"
        #ln -s ${VALUE} ${KEY}
    fi
done


text:
#oauth-enrollment {
  height: 528px;
  padding: 0;
  width: 448px;
}

#oauth-enrollment.saml {
  height: 528px;
  width: 562px;
}

#oauth-enroll-step-contents {
  color: #666;
  height: 100%;
  width: 100%;
}

#oauth-enroll-step-contents > div {
  display: none;
}

.oauth-enroll-state-error #oauth-enroll-step-error,
.oauth-enroll-state-success #oauth-enroll-step-success {
  display: table;
  height: 480px;
  margin: 0 auto;
}

.oauth-enroll-state-working #oauth-enroll-step-signin,
.oauth-enroll-state-attribute-prompt-error
    #oauth-enroll-step-attribute-prompt-error,
.oauth-enroll-state-signin #oauth-enroll-step-signin,
.oauth-enroll-state-attribute-prompt
    #oauth-enroll-step-attribute-prompt {
  display: block;
  height: 100%;
  width: 100%;
}

#oauth-enroll-auth-view-container,
#oauth-enroll-auth-view {
  display: block;
  height: 100%;
  overflow: hidden;
  padding: 0;
  width: 100%;
}

#oauth-enrollment.mode-manual #oauth-enroll-learn-more-link,
#oauth-enrollment.mode-forced #oauth-enroll-learn-more-link,
#oauth-enrollment.mode-recovery #oauth-enroll-learn-more-link {
  display: inline;
}

.oauth-enroll-step-content {
  display: table-cell;
  vertical-align: middle;
}

.oauth-enroll-step-message {
  display: inline-block;
  max-width: 400px;
  text-align: left;
  vertical-align: top;
}

.oauth-enroll-link {
  color: rgb(17, 85, 204);
  cursor: pointer;
  text-decoration: none;
}

.oauth-enroll-button {
  display: none;
}

#oauth-enroll-back-button,
#oauth-enrollment.saml #oauth-enroll-back-button {
  display: none;
}

.oauth-enroll-state-signin #oauth-enroll-back-button {
  display: inline;
}

.oauth-enroll-state-signin.mode-manual #oauth-enroll-cancel-button,
.oauth-enroll-state-signin.mode-forced #oauth-enroll-refresh-button,
.oauth-enroll-state-signin.mode-recovery #oauth-enroll-refresh-button,
.oauth-enroll-state-working.mode-manual #oauth-enroll-cancel-button,
.oauth-enroll-state-working.mode-forced #oauth-enroll-refresh-button,
.oauth-enroll-stain-working.mode-recovery #oauth-enroll-refresh-button,
.oauth-enroll-state-error.mode-manual #oauth-enroll-cancel-button,
.oauth-enroll-state-error.mode-manual #oauth-enroll-done-button,
.oauth-enroll-state-success #oauth-enroll-done-button {
  display: inline;
}

#oobe.oauth-enrollment #header-oauth-enrollment {
  display: block;
}

#oauth-saml-notice-container {
  -webkit-margin-start: 19px;
  left: 0;
  position: absolute;
  right: 0;
  text-align: start;
  top: 15px;
}

#oauth-enrollment.saml {
  padding-top: 47px;
}

#oauth-enrollment.saml #oauth-enrollment-controls,
#oauth-enrollment.saml #oauth-enroll-signin-link-container {
  -webkit-padding-end: 17px;
}

#oauth-enrollment:not(.saml) #oauth-saml-notice-container {
  display: none;
}

#oauth-saml-notice-message {
  color: rgb(106, 106, 106);
  font-size: 13px;
  margin: 0 auto;
}

#oauth-enroll-cancel-button,
#oauth-enroll-back-button,
#oauth-enroll-refresh-button {
  position: absolute;
  top: 10px;
  z-index: 1;
}

#oauth-enroll-cancel-button,
#oauth-enroll-refresh-button {
  color: rgba(0, 0, 0, .54);
  right: 10px;
}

html[dir=rtl] #oauth-enroll-cancel-button,
html[dir=rtl] #oauth-enroll-refresh-button {
  left: 10px;
  right: auto;
}

#oauth-enrollment.saml #oauth-enroll-cancel-button,
#oauth-enrollment.saml #oauth-enroll-refresh-button {
  color: rgba(0, 0, 0, .54);
}

.oauth-enroll-state-signin #oauth-enroll-cancel-button,
.oauth-enroll-state-working #oauth-enroll-cancel-button,
.oauth-enroll-state-signin #oauth-enroll-refresh-button,
.oauth-enroll-state-working #oauth-enroll-refresh-button {
  color: white;
}

#oauth-enroll-back-button {
  color: white;
  left: 10px;
}

html[dir=rtl] #oauth-enroll-back-button {
  -webkit-transform: scaleX(-1);
  left: auto;
  right: 10px;
}

#oauth-enrollment.saml #oauth-enroll-back-button {
  display: none;
}

#oauth-enroll-attribute-prompt-message {
  color: black;
}

#oauth-enroll-skip-button {
  min-width: 0;
}


text:
<md-content class="flex about-content layout-column layout-fill">

About Me!

A

Background

I have always been fascinated by technology. Since elementary school, I've been looking for ways to build cool things in a logical way. I remember my first interaction was drawing a house using Turbo Pascal with Turtle graphics when I was 6.

As time progressed I moved into more complex things. I attended college and graduated with a major in MIS, and during that time I supplemented my studies with online courses on programming.

Not being satisfied with the results of my education, I decided to attend Viking Code School shortly after graduation. VCS is a 15-week intensive program that teaches modern programming languages and frameworks to turn you into a professional full-stack web engineer.

Since then I've worked in multiple exciting projects at the City of Raleigh and continued building helpful tools and applications.

My Recent Projects

I am most familiar working with Ruby, Rails, and PostgreSQL in the back end, and HTML5, CSS3, Javascript, and AngularJS in the front end. Some frameworks and libraries that I use include Bootstrap, and jQuery. Other supporting practices I use are Github, Heroku, AWS, Surge, Sass and Grunt.

One of my recently deployed applications is MapMyJob which is an Angular 1.X application to help young residents of Raleigh find part-time park opportunities near them. You can find more projects in my Github page.

What I'm looking for

I have a strong desire to grow as a programmer. I am always striving to commit better code, and I want to work for a company that expects that of me.

While I would be most comfortable to work at a place which employs the technologies I am familiar with, I pick up languages and frameworks quickly and would be happy to acquire new skills and knowledge.

I am interested in back-end, front-end and full-stack positions.

</md-content>


text:
package org.elasticsearch.test.rest.yaml.parser;

/**
 * Exception thrown whenever there is a problem parsing any of the REST test suite fragment
 */
public class ClientYamlTestParseException extends Exception {

    ClientYamlTestParseException(String message) {
        super(message);
    }

    ClientYamlTestParseException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
Param(
	[string]$buildNumber = "0",
	[string]$preRelease = $null
)

$exists = Test-Path nuget.exe

if ($exists -eq $false) {
	$source = "https://www.nuget.org/nuget.exe"
	Invoke-WebRequest $source -OutFile nuget.exe
}

gci .\source -Recurse "packages.config" |% {
	"Restoring " + $_.FullName
	.\nuget.exe i $_.FullName -o .\source\packages
}

Import-Module .\source\packages\psake.4.4.2\tools\psake.psm1

if(Test-Path Env:\APPVEYOR_BUILD_NUMBER){
	$buildNumber = [int]$Env:APPVEYOR_BUILD_NUMBER
	Write-Host "Using APPVEYOR_BUILD_NUMBER"

	$task = "appVeyor"
}

"Build number $buildNumber"

Invoke-Psake .\default.ps1 $task -framework "4.0x64" -properties @{ buildNumber=$buildNumber; preRelease=$preRelease }

Remove-Module psake


text:
import * as d3 from 'd3';

import BaseDataLayer from './base';
import {merge} from '../../helpers/layouts';

/**
 * @memberof module:LocusZoom_DataLayers~highlight_regions
 */
const default_layout = {
    color: '#CCCCCC',
    fill_opacity: 0.5,
    // By default, it will draw the regions shown.
    filters: null,
    // Most use cases will show a preset list of regions defined in the layout
    //  (if empty, AND layout.fields is not, it could fetch from a data source instead)
    regions: [],
    id_field: 'id',
    start_field: 'start',
    end_field: 'end',
    merge_field: null,
};

/**
 * "Highlight regions with rectangle" data layer.
 * Creates one (or more) continuous 2D rectangles that mark an entire interval, to the full height of the panel.
 *
 * Each individual rectangle can be shown in full, or overlapping ones can be merged (eg, based on same category).
 * The rectangles are generally drawn with partial transparency, and do not respond to mouse events: they are a
 *   useful highlight tool to draw attention to intervals that contain interesting variants.
 *
 * This layer has several useful modes:
 * 1. Draw one or more specified rectangles as provided from:
 *      A. Hard-coded layout (layout.regions)
 *      B. Data fetched from a source (like intervals with start and end coordinates)- as specified in layout.fields
 * 2. Fetch data from an external source, and only render the intervals that match criteria
 *
 * @alias module:LocusZoom_DataLayers~highlight_regions
 * @see {@link module:LocusZoom_DataLayers~BaseDataLayer} for additional layout options
 */
class HighlightRegions extends BaseDataLayer {
    /**
     * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.color='#CCCCCC'] The fill color for each rectangle
     * @param {String|module:LocusZoom_DataLayers~ScalableParameter[]} [layout.fill_opacity=0.5] The opacity (0-1). We recommend partial transparency so that
     *   rectangles do not hide or interfere with adjacent elements.
     * @param {Object[]} [layout.filters] An array of filter entries specifying which intervals to draw annotations for.
     * @param {Object[]} [layout.regions] A hard-coded list of regions. If provided, takes precedence over data fetched from an external source.
     * @param {String} [layout.start_field='start'] The field to use for rectangle start x coordinate
     * @param {String} [layout.end_field='end'] The field to use for rectangle end x coordinate
     * @param {String} [layout.merge_field] If two intervals overlap, they can be "merged" based on a field that
     *  identifies the category (eg, only rectangles of the same category will be merged).
     *  This field must be present in order to trigger merge behavior. This is applied after filters.
     */
    constructor(layout) {
        merge(layout, default_layout);
        if (layout.interaction || layout.behaviors) {
            throw new Error('highlight_regions layer does not support mouse events');
        }

        if (layout.regions.length && layout.namespace && Object.keys(layout.namespace).length) {
            throw new Error('highlight_regions layer can specify "regions" in layout, OR external data "fields", but not both');
        }
        super(...arguments);
    }

    /**
     * Helper method that combines two rectangles if they are the same type of data (category) and occupy the same
     *  area of the plot (will automatically sort the data prior to rendering)
     *
     * When two fields conflict, it will fill in the fields for the last of the items that overlap in that range.
     *   Thus, it is not recommended to use tooltips with this feature, because the tooltip won't reflect real data.
     * @param {Object[]} data
     * @return {Object[]}
     * @private
     */
    _mergeNodes(data) {
        const { end_field, merge_field, start_field } = this.layout;
        if (!merge_field) {
            return data;
        }

        // Ensure data is sorted by start field, with category as a tie breaker
        data.sort((a, b) => {
            // Ensure that data is sorted by category, then start field (ensures overlapping intervals are adjacent)
            return d3.ascending(a[merge_field], b[merge_field]) || d3.ascending(a[start_field], b[start_field]);
        });

        let track_data = [];
        data.forEach(function (cur_item, index) {
            const prev_item = track_data[track_data.length - 1] || cur_item;
            if (cur_item[merge_field] === prev_item[merge_field] && cur_item[start_field] <= prev_item[end_field]) {
                // If intervals overlap, merge the current item with the previous, and append only the merged interval
                const new_start = Math.min(prev_item[start_field], cur_item[start_field]);
                const new_end = Math.max(prev_item[end_field], cur_item[end_field]);
                cur_item = Object.assign({}, prev_item, cur_item, { [start_field]: new_start, [end_field]: new_end });
                track_data.pop();
            }
            track_data.push(cur_item);
        });
        return track_data;
    }

    render() {
        const { x_scale } = this.parent;
        // Apply filters to only render a specified set of points
        let track_data = this.layout.regions.length ? this.layout.regions : this.data;

        // Pseudo identifier for internal use only (regions have no semantic or transition meaning)
        track_data.forEach((d, i) => d.id || (d.id = i));
        track_data = this._applyFilters(track_data);
        track_data = this._mergeNodes(track_data);

        const selection = this.svg.group.selectAll(`rect.lz-data_layer-${this.layout.type}`)
            .data(track_data);

        // Draw rectangles
        selection.enter()
            .append('rect')
            .attr('class', `lz-data_layer-${this.layout.type}`)
            .merge(selection)
            .attr('id', (d) => this.getElementId(d))
            .attr('x', (d) => x_scale(d[this.layout.start_field]))
            .attr('width', (d) => x_scale(d[this.layout.end_field]) - x_scale(d[this.layout.start_field]))
            .attr('height', this.parent.layout.height)
            .attr('fill', (d, i) => this.resolveScalableParameter(this.layout.color, d, i))
            .attr('fill-opacity', (d, i) => this.resolveScalableParameter(this.layout.fill_opacity, d, i));

        // Remove unused elements
        selection.exit()
            .remove();

        // Note: This layer intentionally does not allow tooltips or mouse behaviors, and doesn't affect pan/zoom
        this.svg.group.style('pointer-events', 'none');
    }

    _getTooltipPosition(tooltip) {
        // This layer is for visual highlighting only; it does not allow mouse interaction, drag, or tooltips
        throw new Error('This layer does not support tooltips');
    }
}

export {HighlightRegions as default};


text:
package org.apache.wicket.util.io;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

import org.apache.wicket.util.collections.IntHashMap;
import org.apache.wicket.util.lang.Generics;

/**
 * @author jcompagner
 */
public final class WicketObjectInputStream extends ObjectInputStream
{

	private final IntHashMap<Object> handledObjects = new IntHashMap<Object>();
	private short handleCounter = 0;

	private final DataInputStream in;
	private ClassStreamHandler currentStreamHandler;
	private HandleArrayListStack<Object> stack = new HandleArrayListStack<Object>();
	private HandleArrayListStack<Object> defaultRead = new HandleArrayListStack<Object>();

	/**
	 * Construct.
	 *
	 * @param in
	 * @throws IOException
	 */
	public WicketObjectInputStream(InputStream in) throws IOException
	{
		super();
		this.in = new DataInputStream(in);
	}

	/**
	 * @see java.io.ObjectInputStream#readObjectOverride()
	 */
	@Override
	protected Object readObjectOverride() throws IOException, ClassNotFoundException
	{
		Object value = null;
		int token = in.read();
		if (token == ClassStreamHandler.NULL)
		{
			return null;
		}
		else if (token == ClassStreamHandler.HANDLE)
		{
			short handle = in.readShort();
			value = handledObjects.get(handle);
			if (value == null)
			{
				throw new RuntimeException("Expected to find a handle for " + handle);
			}
		}
		else if (token == ClassStreamHandler.CLASS_DEF)
		{
			short classDef = in.readShort();
			ClassStreamHandler oldStreamHandler = currentStreamHandler;
			currentStreamHandler = ClassStreamHandler.lookup(classDef);
			if (currentStreamHandler.getStreamClass() == String.class)
			{
				value = in.readUTF();
				handledObjects.put(handleCounter++, value);
			}
			else
			{
				try
				{
					value = currentStreamHandler.createObject();
					handledObjects.put(handleCounter++, value);
					stack.push(value);
					if (!currentStreamHandler.invokeReadMethod(this, value))
					{
						currentStreamHandler.readFields(this, value);
					}
					value = currentStreamHandler.readResolve(value);
					stack.pop();
				}
				catch (IllegalArgumentException ex)
				{
					throw new RuntimeException(ex);
				}
				catch (InstantiationException ex)
				{
					throw new RuntimeException(ex);
				}
				catch (IllegalAccessException ex)
				{
					throw new RuntimeException(ex);
				}
				catch (InvocationTargetException ex)
				{
					throw new RuntimeException(ex);
				}
			}
			currentStreamHandler = oldStreamHandler;
		}
		else if (token == ClassStreamHandler.CLASS)
		{
			short classDef = in.readShort();
			ClassStreamHandler lookup = ClassStreamHandler.lookup(classDef);
			value = lookup.getStreamClass();
		}
		else if (token == ClassStreamHandler.ARRAY)
		{
			short classDef = in.readShort();
			ClassStreamHandler lookup = ClassStreamHandler.lookup(classDef);
			int length = in.readInt();
			Object[] array = (Object[])Array.newInstance(lookup.getStreamClass(), length);
			handledObjects.put(handleCounter++, array);
			for (int i = 0; i < array.length; i++)
			{
				array[i] = readObjectOverride();
			}
			value = array;
		}
		else if (token == ClassStreamHandler.PRIMITIVE_ARRAY)
		{
			short classDef = in.readShort();
			ClassStreamHandler lookup = ClassStreamHandler.lookup(classDef);
			value = lookup.readArray(this);
			handledObjects.put(handleCounter++, value);
		}
		else
		{
			throw new RuntimeException("not a valid token found: " + token);
		}
		return value;
	}

	/**
	 * @see java.io.ObjectInputStream#defaultReadObject()
	 */
	@Override
	public void defaultReadObject() throws IOException, ClassNotFoundException
	{
		Object currentObject = stack.peek();
		if (!defaultRead.contains(currentObject))
		{
			defaultRead.add(currentObject);
			currentStreamHandler.readFields(this, currentObject);
		}
	}

	/**
	 * @see java.io.ObjectInputStream#close()
	 */
	@Override
	public void close() throws IOException
	{
		stack = null;
		defaultRead = null;
		currentStreamHandler = null;
		in.close();
	}

	/**
	 * Reads in a boolean.
	 *
	 * @return the boolean read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public boolean readBoolean() throws IOException
	{
		return in.readBoolean();
	}

	/**
	 * Reads an 8 bit byte.
	 *
	 * @return the 8 bit byte read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public byte readByte() throws IOException
	{
		return in.readByte();
	}

	/**
	 * Reads an unsigned 8 bit byte.
	 *
	 * @return the 8 bit byte read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public int readUnsignedByte() throws IOException
	{
		return in.readUnsignedByte();
	}

	/**
	 * Reads a 16 bit char.
	 *
	 * @return the 16 bit char read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public char readChar() throws IOException
	{
		return in.readChar();
	}

	/**
	 * Reads a 16 bit short.
	 *
	 * @return the 16 bit short read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public short readShort() throws IOException
	{
		return in.readShort();
	}

	/**
	 * Reads an unsigned 16 bit short.
	 *
	 * @return the 16 bit short read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public int readUnsignedShort() throws IOException
	{
		return in.readUnsignedShort();
	}

	/**
	 * Reads a 32 bit int.
	 *
	 * @return the 32 bit integer read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public int readInt() throws IOException
	{
		return in.readInt();
	}

	/**
	 * Reads a 64 bit long.
	 *
	 * @return the read 64 bit long.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public long readLong() throws IOException
	{
		return in.readLong();
	}

	/**
	 * Reads a 32 bit float.
	 *
	 * @return the 32 bit float read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public float readFloat() throws IOException
	{
		return in.readFloat();
	}

	/**
	 * Reads a 64 bit double.
	 *
	 * @return the 64 bit double read.
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public double readDouble() throws IOException
	{
		return in.readDouble();
	}

	/**
	 * Reads bytes, blocking until all bytes are read.
	 *
	 * @param buf
	 *            the buffer into which the data is read
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public void readFully(byte[] buf) throws IOException
	{
		in.readFully(buf, 0, buf.length);
	}

	/**
	 * Reads bytes, blocking until all bytes are read.
	 *
	 * @param buf
	 *            the buffer into which the data is read
	 * @param off
	 *            the start offset of the data
	 * @param len
	 *            the maximum number of bytes to read
	 * @throws EOFException
	 *             If end of file is reached.
	 * @throws IOException
	 *             If other I/O error has occurred.
	 */
	@Override
	public void readFully(byte[] buf, int off, int len) throws IOException
	{
		int endoff = off + len;
		if (off < 0 || len < 0 || endoff > buf.length || endoff < 0)
		{
			throw new IndexOutOfBoundsException();
		}
		in.readFully(buf, off, len);
	}

	/**
	 * @see java.io.ObjectInputStream#readUTF()
	 */
	@Override
	public String readUTF() throws IOException
	{
		String s = in.readUTF();
		return s;
	}

	/**
	 * @see java.io.ObjectInputStream#read()
	 */
	@Override
	public int read() throws IOException
	{
		return in.read();
	}

	/**
	 * @see java.io.InputStream#read(byte[])
	 */
	@Override
	public int read(byte[] b) throws IOException
	{
		return in.read(b);
	}

	/**
	 * @see java.io.ObjectInputStream#read(byte[], int, int)
	 */
	@Override
	public int read(byte[] buf, int off, int len) throws IOException
	{
		return in.read(buf, off, len);
	}

	/**
	 * @see java.io.ObjectInputStream#readFields()
	 */
	@Override
	public GetField readFields() throws IOException, ClassNotFoundException
	{
		GetFieldImpl field = new GetFieldImpl();
		field.read();
		return field;
	}

	private class GetFieldImpl extends GetField
	{
		private final HashMap<String, Object> values = Generics.newHashMap();

		private void read() throws IOException, ClassNotFoundException
		{
			short token = readShort();
			ClassStreamHandler lookup = ClassStreamHandler.lookup(boolean.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, readBoolean() ? Boolean.TRUE : Boolean.FALSE);
				}
				token = readShort();
				if (token == ClassStreamHandler.NULL)
				{
					return;
				}
			}
			lookup = ClassStreamHandler.lookup(byte.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, new Byte(readByte()));
				}
				token = readShort();
				if (token == ClassStreamHandler.NULL)
				{
					return;
				}
			}
			lookup = ClassStreamHandler.lookup(short.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, new Short(readShort()));
				}
				token = readShort();
				if (token == ClassStreamHandler.NULL)
				{
					return;
				}
			}
			lookup = ClassStreamHandler.lookup(char.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, new Character(readChar()));
				}
				token = readShort();
				if (token == ClassStreamHandler.NULL)
				{
					return;
				}
			}
			lookup = ClassStreamHandler.lookup(int.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, new Integer(readInt()));
				}
				token = readShort();
				if (token == ClassStreamHandler.NULL)
				{
					return;
				}
			}
			lookup = ClassStreamHandler.lookup(long.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, new Long(readLong()));
				}
				token = readShort();
				if (token == ClassStreamHandler.NULL)
				{
					return;
				}
			}
			lookup = ClassStreamHandler.lookup(float.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, new Float(readFloat()));
				}
				token = readShort();
				if (token == ClassStreamHandler.NULL)
				{
					return;
				}
			}
			lookup = ClassStreamHandler.lookup(double.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, new Double(readDouble()));
				}
				token = readShort();
				if (token == ClassStreamHandler.NULL)
				{
					return;
				}
			}
			lookup = ClassStreamHandler.lookup(Serializable.class);
			if (token == lookup.getClassId())
			{
				short count = readShort();
				for (int i = 0; i < count; i++)
				{
					String key = (String)readObjectOverride();
					values.put(key, readObjectOverride());
				}
				token = readShort();
			}
			if (token != ClassStreamHandler.NULL)
			{
				throw new RuntimeException("Expected NULL end byte");
			}
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#defaulted(java.lang.String)
		 */
		@Override
		public boolean defaulted(String name) throws IOException
		{
			return values.get(name) == null;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, byte)
		 */
		@Override
		public byte get(String name, byte val) throws IOException
		{
			Object o = values.get(name);
			if (o instanceof Byte)
			{
				return ((Byte)o).byteValue();
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, char)
		 */
		@Override
		public char get(String name, char val) throws IOException
		{
			Object o = values.get(name);
			if (o instanceof Byte)
			{
				return ((Character)o).charValue();
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, double)
		 */
		@Override
		public double get(String name, double val) throws IOException
		{
			Object o = values.get(name);
			if (o instanceof Double)
			{
				return ((Double)o).doubleValue();
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, float)
		 */
		@Override
		public float get(String name, float val) throws IOException
		{
			Object o = values.get(name);
			if (o instanceof Float)
			{
				return ((Float)o).floatValue();
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, int)
		 */
		@Override
		public int get(String name, int val) throws IOException
		{
			Object o = values.get(name);
			if (o instanceof Integer)
			{
				return ((Integer)o).intValue();
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, long)
		 */
		@Override
		public long get(String name, long val) throws IOException
		{
			Object o = values.get(name);
			if (o instanceof Long)
			{
				return ((Long)o).longValue();
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, short)
		 */
		@Override
		public short get(String name, short val) throws IOException
		{
			Object o = values.get(name);
			if (o instanceof Short)
			{
				return ((Short)o).shortValue();
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, boolean)
		 */
		@Override
		public boolean get(String name, boolean val) throws IOException
		{
			Object o = values.get(name);
			if (o instanceof Boolean)
			{
				return ((Boolean)o).booleanValue();
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#get(java.lang.String, java.lang.Object)
		 */
		@Override
		public Object get(String name, Object val) throws IOException
		{
			Object o = values.get(name);
			if (o != null)
			{
				return o;
			}
			return val;
		}

		/**
		 * @see java.io.ObjectInputStream.GetField#getObjectStreamClass()
		 */
		@Override
		public ObjectStreamClass getObjectStreamClass()
		{
			return null;
		}

	}
}


text:
        Let's do some nice ETL for this

        Sign in

        {{ errors }}

        <form class="form-horizontal" name="form" ng-submit="save(form)">

              Data Source Metadata (Required)

              <select name="dataorg" chosen class="form-control"
                ng-model="dataset.dataorg" disable-search="true"
                ng-options="c.value as c.label for c in reference.dataorgs">
              </select>

              Name

              <input name="name" ng-model="dataset.name" class="form-control"
                placeholder="Name_Of_Dataset">

              Label

              <input name="label" ng-model="dataset.label" class="form-control"
                placeholder="Name of Dataset">

              Description

              <textarea ng-model="dataset.description" class="xxlarge form-control"
                rows="4" name="description"></textarea>

              Data Type

              <select name="dataType" class="form-control"
                ng-model="dataset.dataType" disable-search="true"
                ng-options="c.value as c.label for c in reference.dataTypes">
              </select>

              <button type="submit" class="btn btn-success">
                Save
              </button>

        </form>


text:
DGVocabulary = function () {

};

DGVocabulary._MSG = {};
DGVocabulary._MSG["alert_select_row"] = "Musíte vybrat jeden nebo více řádků provést tuto operaci!";
DGVocabulary._MSG["alert_perform_operation"] = "Jste si jisti, že chcete provést tuto operaci?";
DGVocabulary._MSG["alert_perform_operation_delete"] = "Jste si jisti, že chcete provádět operaci odstranění?";
DGVocabulary._MSG["alert_perform_operation_clone"] = "Jste si jisti, že chcete provádět operaci klon?";
DGVocabulary._MSG["alert_blocked_in_demo"] = "Tato operace je blokována v Demo verzi!";
DGVocabulary._MSG["cookies_required"] = "Tato operace vyžaduje, aby Váš prohlížeč akceptuje cookies! Prosím, zapněte cookies přijímá.";
DGVocabulary._MSG["extension_not_allowed"] = "Soubory s příponou vybraného nejsou povoleny.";
DGVocabulary._MSG["need_upload_file"] = "Musíte nahrát soubor nebo image před update! Prosím, klikněte na odkaz Nahrát.";
DGVocabulary._MSG["please_reenter"] = "Zadejte prosím znovu!";
DGVocabulary._MSG["upload_file_size_alert"] = "Soubor, který se pokoušíte nahrát, je větší než maximální povolená velikost: ";


text:
#if !defined(_MD5_H)
#define _MD5_H

 /* Any 32-bit or wider unsigned integer data type will do */
typedef unsigned int MD5_u32plus;

typedef struct {
    MD5_u32plus lo, hi;
    MD5_u32plus a, b, c, d;
    unsigned char buffer[64];
    MD5_u32plus block[16];
} EX_MD5_CTX;

extern void Ex_MD5_Init(EX_MD5_CTX *ctx);
extern void Ex_MD5_Update(EX_MD5_CTX *ctx, const void *data, unsigned long size);
extern void Ex_MD5_Final(unsigned char *result, EX_MD5_CTX *ctx);

#endif


text:
#include "config.h"
#include "LayoutState.h"

#include "ColumnInfo.h"
#include "RenderArena.h"
#include "RenderFlowThread.h"
#include "RenderInline.h"
#include "RenderLayer.h"
#include "RenderView.h"

namespace WebCore {

LayoutState::LayoutState(LayoutState* prev, RenderBox* renderer, const LayoutSize& offset, LayoutUnit pageLogicalHeight, bool pageLogicalHeightChanged, ColumnInfo* columnInfo)
    : m_columnInfo(columnInfo)
    , m_lineGrid(0)
    , m_next(prev)
#if ENABLE(CSS_EXCLUSIONS)
    , m_exclusionShapeInsideInfo(0)
#endif
#ifndef NDEBUG
    , m_renderer(renderer)
#endif
{
    ASSERT(m_next);

    bool fixed = renderer->isOutOfFlowPositioned() && renderer->style()->position() == FixedPosition;
    if (fixed) {
        // FIXME: This doesn't work correctly with transforms.
        FloatPoint fixedOffset = renderer->view()->localToAbsolute(FloatPoint(), IsFixed);
        m_paintOffset = LayoutSize(fixedOffset.x(), fixedOffset.y()) + offset;
    } else
        m_paintOffset = prev->m_paintOffset + offset;

    if (renderer->isOutOfFlowPositioned() && !fixed) {
        if (RenderObject* container = renderer->container()) {
            if (container->isInFlowPositioned() && container->isRenderInline())
                m_paintOffset += toRenderInline(container)->offsetForInFlowPositionedInline(renderer);
        }
    }

    m_layoutOffset = m_paintOffset;

    if (renderer->isInFlowPositioned() && renderer->hasLayer())
        m_paintOffset += renderer->layer()->offsetForInFlowPosition();

    m_clipped = !fixed && prev->m_clipped;
    if (m_clipped)
        m_clipRect = prev->m_clipRect;

    if (renderer->hasOverflowClip()) {
        LayoutRect clipRect(toPoint(m_paintOffset) + renderer->view()->layoutDelta(), renderer->cachedSizeForOverflowClip());
        if (m_clipped)
            m_clipRect.intersect(clipRect);
        else {
            m_clipRect = clipRect;
            m_clipped = true;
        }

        m_paintOffset -= renderer->scrolledContentOffset();
    }

    // If we establish a new page height, then cache the offset to the top of the first page.
    // We can compare this later on to figure out what part of the page we're actually on,
    if (pageLogicalHeight || m_columnInfo || renderer->isRenderFlowThread()) {
        m_pageLogicalHeight = pageLogicalHeight;
        bool isFlipped = renderer->style()->isFlippedBlocksWritingMode();
        m_pageOffset = LayoutSize(m_layoutOffset.width() + (!isFlipped ? renderer->borderLeft() + renderer->paddingLeft() : renderer->borderRight() + renderer->paddingRight()),
                               m_layoutOffset.height() + (!isFlipped ? renderer->borderTop() + renderer->paddingTop() : renderer->borderBottom() + renderer->paddingBottom()));
        m_pageLogicalHeightChanged = pageLogicalHeightChanged;
    } else {
        // If we don't establish a new page height, then propagate the old page height and offset down.
        m_pageLogicalHeight = m_next->m_pageLogicalHeight;
        m_pageLogicalHeightChanged = m_next->m_pageLogicalHeightChanged;
        m_pageOffset = m_next->m_pageOffset;

        // Disable pagination for objects we don't support. For now this includes overflow:scroll/auto, inline blocks and
        // writing mode roots.
        if (renderer->isUnsplittableForPagination())
            m_pageLogicalHeight = 0;
    }

    // Propagate line grid information.
    propagateLineGridInfo(renderer);

    if (!m_columnInfo)
        m_columnInfo = m_next->m_columnInfo;

#if ENABLE(CSS_EXCLUSIONS)
    if (renderer->isRenderBlock()) {
        m_exclusionShapeInsideInfo = toRenderBlock(renderer)->exclusionShapeInsideInfo();
        if (!m_exclusionShapeInsideInfo)
            m_exclusionShapeInsideInfo = m_next->m_exclusionShapeInsideInfo;
    }
#endif

    m_layoutDelta = m_next->m_layoutDelta;
#if !ASSERT_DISABLED && ENABLE(SATURATED_LAYOUT_ARITHMETIC)
    m_layoutDeltaXSaturated = m_next->m_layoutDeltaXSaturated;
    m_layoutDeltaYSaturated = m_next->m_layoutDeltaYSaturated;
#endif

    m_isPaginated = m_pageLogicalHeight || m_columnInfo || renderer->isRenderFlowThread();

    if (lineGrid() && renderer->hasColumns() && renderer->style()->hasInlineColumnAxis())
        computeLineGridPaginationOrigin(renderer);

    // If we have a new grid to track, then add it to our set.
    if (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isBlockFlow())
        establishLineGrid(toRenderBlock(renderer));

    // FIXME: <http://bugs.webkit.org/show_bug.cgi?id=13443> Apply control clip if present.
}

LayoutState::LayoutState(RenderObject* root)
    : m_clipped(false)
    , m_isPaginated(false)
    , m_pageLogicalHeightChanged(false)
#if !ASSERT_DISABLED && ENABLE(SATURATED_LAYOUT_ARITHMETIC)
    , m_layoutDeltaXSaturated(false)
    , m_layoutDeltaYSaturated(false)
#endif
    , m_columnInfo(0)
    , m_lineGrid(0)
    , m_next(0)
#if ENABLE(CSS_EXCLUSIONS)
    , m_exclusionShapeInsideInfo(0)
#endif
    , m_pageLogicalHeight(0)
#ifndef NDEBUG
    , m_renderer(root)
#endif
{
    RenderObject* container = root->container();
    FloatPoint absContentPoint = container->localToAbsolute(FloatPoint(), UseTransforms | SnapOffsetForTransforms);
    m_paintOffset = LayoutSize(absContentPoint.x(), absContentPoint.y());

    if (container->hasOverflowClip()) {
        m_clipped = true;
        RenderBox* containerBox = toRenderBox(container);
        m_clipRect = LayoutRect(toPoint(m_paintOffset), containerBox->cachedSizeForOverflowClip());
        m_paintOffset -= containerBox->scrolledContentOffset();
    }
}

#ifndef NDEBUG
static bool inLayoutStateDestroy;
#endif

void LayoutState::destroy(RenderArena* renderArena)
{
#ifndef NDEBUG
    inLayoutStateDestroy = true;
#endif
    delete this;
#ifndef NDEBUG
    inLayoutStateDestroy = false;
#endif
    renderArena->free(*(size_t*)this, this);
}

void* LayoutState::operator new(size_t sz, RenderArena* renderArena)
{
    return renderArena->allocate(sz);
}

void LayoutState::operator delete(void* ptr, size_t sz)
{
    ASSERT(inLayoutStateDestroy);
    *(size_t*)ptr = sz;
}

void LayoutState::clearPaginationInformation()
{
    m_pageLogicalHeight = m_next->m_pageLogicalHeight;
    m_pageOffset = m_next->m_pageOffset;
    m_columnInfo = m_next->m_columnInfo;
}

LayoutUnit LayoutState::pageLogicalOffset(RenderBox* child, LayoutUnit childLogicalOffset) const
{
    if (child->isHorizontalWritingMode())
        return m_layoutOffset.height() + childLogicalOffset - m_pageOffset.height();
    return m_layoutOffset.width() + childLogicalOffset - m_pageOffset.width();
}

void LayoutState::addForcedColumnBreak(RenderBox* child, LayoutUnit childLogicalOffset)
{
    if (!m_columnInfo || m_columnInfo->columnHeight())
        return;
    m_columnInfo->addForcedBreak(pageLogicalOffset(child, childLogicalOffset));
}

void LayoutState::propagateLineGridInfo(RenderBox* renderer)
{
    // Disable line grids for objects we don't support. For now this includes overflow:scroll/auto, inline blocks and
    // writing mode roots.
    if (!m_next || renderer->isUnsplittableForPagination())
        return;

    m_lineGrid = m_next->m_lineGrid;
    m_lineGridOffset = m_next->m_lineGridOffset;
    m_lineGridPaginationOrigin = m_next->m_lineGridPaginationOrigin;
}

void LayoutState::establishLineGrid(RenderBlock* block)
{
    // First check to see if this grid has been established already.
    if (m_lineGrid) {
        if (m_lineGrid->style()->lineGrid() == block->style()->lineGrid())
            return;
        RenderBlock* currentGrid = m_lineGrid;
        for (LayoutState* currentState = m_next; currentState; currentState = currentState->m_next) {
            if (currentState->m_lineGrid == currentGrid)
                continue;
            currentGrid = currentState->m_lineGrid;
            if (!currentGrid)
                break;
            if (currentGrid->style()->lineGrid() == block->style()->lineGrid()) {
                m_lineGrid = currentGrid;
                m_lineGridOffset = currentState->m_lineGridOffset;
                return;
            }
        }
    }

    // We didn't find an already-established grid with this identifier. Our render object establishes the grid.
    m_lineGrid = block;
    m_lineGridOffset = m_layoutOffset;
}

void LayoutState::computeLineGridPaginationOrigin(RenderBox* renderer)
{
    // We need to cache a line grid pagination origin so that we understand how to reset the line grid
    // at the top of each column.
    // Get the current line grid and offset.
    if (!lineGrid() || lineGrid()->style()->writingMode() != renderer->style()->writingMode())
        return;

    // Get the hypothetical line box used to establish the grid.
    RootInlineBox* lineGridBox = lineGrid()->lineGridBox();
    if (!lineGridBox)
        return;

    bool isHorizontalWritingMode = lineGrid()->isHorizontalWritingMode();

    LayoutUnit lineGridBlockOffset = isHorizontalWritingMode ? lineGridOffset().height() : lineGridOffset().width();

    // Now determine our position on the grid. Our baseline needs to be adjusted to the nearest baseline multiple
    // as established by the line box.
    // FIXME: Need to handle crazy line-box-contain values that cause the root line box to not be considered. I assume
    // the grid should honor line-box-contain.
    LayoutUnit gridLineHeight = lineGridBox->lineBottomWithLeading() - lineGridBox->lineTopWithLeading();
    if (!gridLineHeight)
        return;

    LayoutUnit firstLineTopWithLeading = lineGridBlockOffset + lineGridBox->lineTopWithLeading();

    if (isPaginated() && pageLogicalHeight()) {
        LayoutUnit pageLogicalTop = renderer->isHorizontalWritingMode() ? m_pageOffset.height() : m_pageOffset.width();
        if (pageLogicalTop > firstLineTopWithLeading) {
            // Shift to the next highest line grid multiple past the page logical top. Cache the delta
            // between this new value and the page logical top as the pagination origin.
            LayoutUnit remainder = roundToInt(pageLogicalTop - firstLineTopWithLeading) % roundToInt(gridLineHeight);
            LayoutUnit paginationDelta = gridLineHeight - remainder;
            if (isHorizontalWritingMode)
                m_lineGridPaginationOrigin.setHeight(paginationDelta);
            else
                m_lineGridPaginationOrigin.setWidth(paginationDelta);
        }
    }
}

} // namespace WebCore