<commit_before>
angular.module('ctrls', [])
.controller('ModelCount', ['$scope', 'ModelViewer', function($scope, MV) {
    $scope.MV = MV;
}])

.controller('Documentation',
['$scope', '$state',
function($scope, $state) {
    console.log('state', $state)
}])

.controller('MediaDropdown', ['$scope', 'MS', '$q', 'uiTools',
function($s, MS, $q, uiTools) {
    var self = this;

    $s.relativeTime = uiTools.relativeTime;
    $s.filterPublic = true;

    self.form = $s.form;

    self.isDisabled = false;
    self.querySearch = querySearch;
    self.selectedItemChange = selectedItemChange;
    self.searchTextChange = searchTextChange;

    MS.listPublicMedia()
        .then(function(media) {
            $s.media = media;
        })

    MS.listMyMedia()
        .then(function(media) {
            $s.myMedia = media;
        }).catch(function(e) {
            $s.myMedia = []; // media folder may not exist
        })

    function querySearch (query) {
        if (!$s.filterPublic)
            var results = query ? $s.myMedia.filter( createFilterFor(query) ) : $s.myMedia;
        else
            var results = query ? $s.media.filter( createFilterFor(query) ) : $s.media;
        return results.slice(0, 50);
    }

    function searchTextChange(text) {

    }
    function selectedItemChange(item) {
        self.form.media = item.path;
    }

    function createFilterFor(query) {
        var lowercaseQuery = angular.lowercase(query);
        return function filterFn(state) {
            return (state.value.indexOf(lowercaseQuery) >= 0);
        };
    }

}])

.controller('CompoundDropdown', ['$scope', 'Biochem',
function($scope, Biochem) {
    var self = this;
    self.form = $scope.form

    self.readonly = false;
    self.selectedItem = null;
    self.searchText = null;
    self.querySearch = querySearch;
    self.compounds = [];
    self.numberChips = [];
    self.numberChips2 = [];
    self.numberBuffer = '';

    function querySearch (query) {
        return Biochem.get('model_compound', {query: query, limit: 10})
                .then(function(res) {
                    var data = [];
                    for (var i in res.docs) {
                        var doc = res.docs[i];

                        if (doc.id === 'cpd00000') continue;
                        data.push({name: doc.name,
                                  id: doc.id})
                    }

                    return data;
                })
    }
}])

.controller('ReactionDropdown', ['$scope', 'Biochem',
function($scope, Biochem) {
    var self = this;
    self.form = $scope.form

    self.readonly = false;
    self.selectedItem = null;
    self.searchText = null;
    self.querySearch = querySearch;
    self.reactions = [];
    self.numberChips = [];
    self.numberChips2 = [];
    self.numberBuffer = '';

    function querySearch (query) {
        return Biochem.get('model_reaction', {query: query, limit: 10})
                .then(function(res) {
                    var data = [];
                    for (var i in res.docs) {
                        var doc = res.docs[i];

                        if (doc.id === 'rxn00000') continue;
                        data.push({name: doc.name,
                                  id: doc.id})
                    }

                    return data;
                })
    }
}])

.controller('SelectedData', ['$scope', '$mdDialog', 'ModelViewer',
function($scope, $dialog, MV) {
    $scope.MV = MV;

    $scope.openFBAView = function(ev, $index, item) {
        $dialog.show({
            templateUrl: 'app/views/dialogs/fba.html',
            // targetEvent: ev, //fixme: bug report
            controller: ['$scope', '$http', 'ModelViewer',
                function($scope, $http, MV) {
                $scope.MV = MV;
                $scope.item = item;
                $scope.selectedIndex = $index;

                MV.getRelatedFBAs([{workspace: item.model.ws, name: item.model.name}])
                  .then(function(fbas) {
                      for (var i=0; i<fbas.length; i++) {
                          if ( $scope.item.fba.name === fbas[i].name &&
                               $scope.item.fba.ws === fbas[i].ws)
                               $scope.activeFBAIndex = i;
                      }
                      $scope.fbas = fbas;
                  })

                $scope.selectFBA = function($index, newFBA) {
                    var newItem = {model: {name: item.model.name, ws: item.model.ws },
                                   fba: {name: newFBA.name, ws: newFBA.ws},
                                   org: item.org,
                                   media: newFBA.media};

                    MV.swapItem($scope.selectedIndex, newItem);
                    $scope.activeFBAIndex = $index;
                    $scope.item = newItem;
                    $dialog.hide();

                    //angular.element(ev.target).parent().fadeOut(150)
                    //       .fadeIn(200);
                }

                $scope.cancel = function(){
                    $dialog.hide();
                }

                $scope.select = function(item){

                }
            }]
        })
    }

}])

.controller('SideNav',
['$scope', '$mdSidenav',
function($scope, $mdSidenav) {
    $scope.close = function() {
        $mdSidenav('right').toggle();
    }
}])

.controller('LeftCtrl', ['$scope', '$timeout', '$mdSidenav', '$log',
function ($scope, $timeout, $mdSidenav, $log) {

    $scope.close = function () {
        $mdSidenav('left').close()
          .then(function () {
              $log.debug("close LEFT is done");
          });
    };
}])

.service('VizOptions', [function() {

    // default for abs flux
    this.flux = 'absFlux';

}])

.service('ViewOptions', [function() {
    /**
     *  Options that persist across pages
    */

    var defaultSettings = {
        organismType: 'Microbes',
        viewMyGenomes: false,
        wsBrowser: {showHidden: false}
    };

    // get stored options
    var options = JSON.parse( localStorage.getItem('ViewOptions') );

    // verify previous settings or reset
    if (!options || !angular.equals(Object.keys(options), Object.keys(defaultSettings)) ) {
        options = defaultSettings;
        localStorage.setItem('ViewOptions', JSON.stringify(options) );
    }

    this.set = function(key, value) {
        options[key] = value;
        localStorage.setItem('ViewOptions', JSON.stringify(options) )
        return options[key];
    }

    this.get = function(key) {
        //if (key === 'organismType') return defaultSettings.organismType;
        return options[key];
    }

}])

.service('Session', [function() {
    this.tabs = {},
    this.opts = {};

    this.setTab = function(state, tab) {
        this.tabs[state.current.name] = tab.tabIndex;
    }

    this.getTab = function(state) {
        return this.tabs[state.current.name] || null;
    }

    this.setOpts = function(state, table, opts) {
        this.opts[state.current.name+'-'+table] = opts;
    }

    this.getOpts = function(state, table) {
        return this.opts[state.current.name+'-'+table] || null;
    }
}])

.controller('Publications',
['$scope', '$http', 'uiTools', 'config',
function($s, $http, uiTools, config) {

    $s.reversed = false; // sort by year

    var url = config.services.ms_rest_url;
    $http.get(url+'/publications')
        .then(function(res) {
            var d = res.data;
            for (var i=0; i<d.length; i++) {
                d[i].authors = d[i].authors.join('; ')
            }
            $s.pubs = d;
        })
}])

.controller('Team',
['$scope', '$stateParams',
function($s, $stateParams) {
    console.log('here')

}])

.filter('highlight', ['$sce', function($sce) {
    return function(text, phrase) {
        if (phrase && text) text = text.replace(new RegExp('('+phrase+')', 'gi'),
            '$1')
            return $sce.trustAsHtml(text);
    }
}])

.controller('API',
['$scope', '$http', 'uiTools', 'config',
function($s, $http, uiTools, config) {
    $s.url = config.services.ms_rest_url;
    $s.version = 'v0';

    $http.get('/app/views/docs/api-docs.json')
        .then(function(res) {
            var data = res.data;
            //console.log('data', data)

            var api = [];

            for (var i in data) {
                var tags = data[i][0].tags;

                var endpoint = {params: []}
                for (var j in tags) {
                    var tagObj = tags[j];
                    if (tagObj.tag === 'api')
                        endpoint.api = tagObj
                    else if (tagObj.tag === 'apiName')
                        endpoint.name = tagObj
                    else if (tagObj.tag === 'apiSuccess')
                        endpoint.success = tagObj
                    else if (tagObj.tag === 'apiSampleRequest')
                        endpoint.sampleRequest = tagObj
                    else if (tagObj.tag === 'apiParam')
                        endpoint.params.push(tagObj)
                    else if (tagObj.tag === 'apiSuccessExample') {
                        endpoint.successExample = tagObj
                        endpoint.successExample.header = tagObj.description.split('\n')[0]

                        var structure = tagObj.description.split('OK')[1];

                        endpoint.successExample.structure = syntaxHighlight(JSON.stringify(
                            JSON.parse( tagObj.description.split('OK')[1] ), null, 2)
                        ) ;
                    }

                    //apiSuccess
                }

                api.push(endpoint)
            }

            console.log('api',  api)

            $s.api = api;
        })

    function syntaxHighlight(json) {
        json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
        return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
            var cls = 'number';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'key';
                } else {
                    cls = 'string';
                }
            } else if (/true|false/.test(match)) {
                cls = 'boolean';
            } else if (/null/.test(match)) {
                cls = 'null';
            }
            return '' + match + '';
        });
    }
}])

.controller('UserStatus',
['$scope', '$stateParams', 'Auth',
function($s, $stateParams, auth) {
    console.log('user status controller')

    // join room user-status
    var socket = io.connect('http://0.0.0.0:3000/user-status');

    console.log('auth.token', auth.token)

    socket.on('connect', function() {

        // initial request for meta data
        socket.emit('request meta', function(meta) {
            //console.log('data', meta)

            $s.$apply(function() {
                $s.meta = meta;
            })
        })

        // subsequent count updates
        socket.on('update meta', function(meta) {
            //console.log('trying to update to meta', meta)
            $s.$apply(function() {
                $s.meta = meta;
            })
        })
    })
}])

.controller('Proto',
['$scope', '$stateParams', '$timeout',
function($scope, $stateParams, $timeout) {

}])
<commit_msg>uh, force microbes, in case user hasn't been to site in ~year<commit_after>
angular.module('ctrls', [])
.controller('ModelCount', ['$scope', 'ModelViewer', function($scope, MV) {
    $scope.MV = MV;
}])

.controller('Documentation',
['$scope', '$state',
function($scope, $state) {
    console.log('state', $state)
}])

.controller('MediaDropdown', ['$scope', 'MS', '$q', 'uiTools',
function($s, MS, $q, uiTools) {
    var self = this;

    $s.relativeTime = uiTools.relativeTime;
    $s.filterPublic = true;

    self.form = $s.form;

    self.isDisabled = false;
    self.querySearch = querySearch;
    self.selectedItemChange = selectedItemChange;
    self.searchTextChange = searchTextChange;

    MS.listPublicMedia()
        .then(function(media) {
            $s.media = media;
        })

    MS.listMyMedia()
        .then(function(media) {
            $s.myMedia = media;
        }).catch(function(e) {
            $s.myMedia = []; // media folder may not exist
        })

    function querySearch (query) {
        if (!$s.filterPublic)
            var results = query ? $s.myMedia.filter( createFilterFor(query) ) : $s.myMedia;
        else
            var results = query ? $s.media.filter( createFilterFor(query) ) : $s.media;
        return results.slice(0, 50);
    }

    function searchTextChange(text) {

    }
    function selectedItemChange(item) {
        self.form.media = item.path;
    }

    function createFilterFor(query) {
        var lowercaseQuery = angular.lowercase(query);
        return function filterFn(state) {
            return (state.value.indexOf(lowercaseQuery) >= 0);
        };
    }

}])

.controller('CompoundDropdown', ['$scope', 'Biochem',
function($scope, Biochem) {
    var self = this;
    self.form = $scope.form

    self.readonly = false;
    self.selectedItem = null;
    self.searchText = null;
    self.querySearch = querySearch;
    self.compounds = [];
    self.numberChips = [];
    self.numberChips2 = [];
    self.numberBuffer = '';

    function querySearch (query) {
        return Biochem.get('model_compound', {query: query, limit: 10})
                .then(function(res) {
                    var data = [];
                    for (var i in res.docs) {
                        var doc = res.docs[i];

                        if (doc.id === 'cpd00000') continue;
                        data.push({name: doc.name,
                                  id: doc.id})
                    }

                    return data;
                })
    }
}])

.controller('ReactionDropdown', ['$scope', 'Biochem',
function($scope, Biochem) {
    var self = this;
    self.form = $scope.form

    self.readonly = false;
    self.selectedItem = null;
    self.searchText = null;
    self.querySearch = querySearch;
    self.reactions = [];
    self.numberChips = [];
    self.numberChips2 = [];
    self.numberBuffer = '';

    function querySearch (query) {
        return Biochem.get('model_reaction', {query: query, limit: 10})
                .then(function(res) {
                    var data = [];
                    for (var i in res.docs) {
                        var doc = res.docs[i];

                        if (doc.id === 'rxn00000') continue;
                        data.push({name: doc.name,
                                  id: doc.id})
                    }

                    return data;
                })
    }
}])

.controller('SelectedData', ['$scope', '$mdDialog', 'ModelViewer',
function($scope, $dialog, MV) {
    $scope.MV = MV;

    $scope.openFBAView = function(ev, $index, item) {
        $dialog.show({
            templateUrl: 'app/views/dialogs/fba.html',
            // targetEvent: ev, //fixme: bug report
            controller: ['$scope', '$http', 'ModelViewer',
                function($scope, $http, MV) {
                $scope.MV = MV;
                $scope.item = item;
                $scope.selectedIndex = $index;

                MV.getRelatedFBAs([{workspace: item.model.ws, name: item.model.name}])
                  .then(function(fbas) {
                      for (var i=0; i<fbas.length; i++) {
                          if ( $scope.item.fba.name === fbas[i].name &&
                               $scope.item.fba.ws === fbas[i].ws)
                               $scope.activeFBAIndex = i;
                      }
                      $scope.fbas = fbas;
                  })

                $scope.selectFBA = function($index, newFBA) {
                    var newItem = {model: {name: item.model.name, ws: item.model.ws },
                                   fba: {name: newFBA.name, ws: newFBA.ws},
                                   org: item.org,
                                   media: newFBA.media};

                    MV.swapItem($scope.selectedIndex, newItem);
                    $scope.activeFBAIndex = $index;
                    $scope.item = newItem;
                    $dialog.hide();

                    //angular.element(ev.target).parent().fadeOut(150)
                    //       .fadeIn(200);
                }

                $scope.cancel = function(){
                    $dialog.hide();
                }

                $scope.select = function(item){

                }
            }]
        })
    }

}])

.controller('SideNav',
['$scope', '$mdSidenav',
function($scope, $mdSidenav) {
    $scope.close = function() {
        $mdSidenav('right').toggle();
    }
}])

.controller('LeftCtrl', ['$scope', '$timeout', '$mdSidenav', '$log',
function ($scope, $timeout, $mdSidenav, $log) {

    $scope.close = function () {
        $mdSidenav('left').close()
          .then(function () {
              $log.debug("close LEFT is done");
          });
    };
}])

.service('VizOptions', [function() {

    // default for abs flux
    this.flux = 'absFlux';

}])

.service('ViewOptions', [function() {
    /**
     *  Options that persist across pages
    */

    var defaultSettings = {
        organismType: 'Microbes',
        viewMyGenomes: false,
        wsBrowser: {showHidden: false}
    };

    // get stored options
    var options = JSON.parse( localStorage.getItem('ViewOptions') );

    // verify previous settings or reset
    if (!options || !angular.equals(Object.keys(options), Object.keys(defaultSettings)) ) {
        options = defaultSettings;
        localStorage.setItem('ViewOptions', JSON.stringify(options) );
    }

    this.set = function(key, value) {
        options[key] = value;
        localStorage.setItem('ViewOptions', JSON.stringify(options) )
        return options[key];
    }

    this.get = function(key) {
        if (key === 'organismType') return defaultSettings.organismType;
        return options[key];
    }

}])

.service('Session', [function() {
    this.tabs = {},
    this.opts = {};

    this.setTab = function(state, tab) {
        this.tabs[state.current.name] = tab.tabIndex;
    }

    this.getTab = function(state) {
        return this.tabs[state.current.name] || null;
    }

    this.setOpts = function(state, table, opts) {
        this.opts[state.current.name+'-'+table] = opts;
    }

    this.getOpts = function(state, table) {
        return this.opts[state.current.name+'-'+table] || null;
    }
}])

.controller('Publications',
['$scope', '$http', 'uiTools', 'config',
function($s, $http, uiTools, config) {

    $s.reversed = false; // sort by year

    var url = config.services.ms_rest_url;
    $http.get(url+'/publications')
        .then(function(res) {
            var d = res.data;
            for (var i=0; i<d.length; i++) {
                d[i].authors = d[i].authors.join('; ')
            }
            $s.pubs = d;
        })
}])

.controller('Team',
['$scope', '$stateParams',
function($s, $stateParams) {
    console.log('here')

}])

.filter('highlight', ['$sce', function($sce) {
    return function(text, phrase) {
        if (phrase && text) text = text.replace(new RegExp('('+phrase+')', 'gi'),
            '$1')
            return $sce.trustAsHtml(text);
    }
}])

.controller('API',
['$scope', '$http', 'uiTools', 'config',
function($s, $http, uiTools, config) {
    $s.url = config.services.ms_rest_url;
    $s.version = 'v0';

    $http.get('/app/views/docs/api-docs.json')
        .then(function(res) {
            var data = res.data;
            //console.log('data', data)

            var api = [];

            for (var i in data) {
                var tags = data[i][0].tags;

                var endpoint = {params: []}
                for (var j in tags) {
                    var tagObj = tags[j];
                    if (tagObj.tag === 'api')
                        endpoint.api = tagObj
                    else if (tagObj.tag === 'apiName')
                        endpoint.name = tagObj
                    else if (tagObj.tag === 'apiSuccess')
                        endpoint.success = tagObj
                    else if (tagObj.tag === 'apiSampleRequest')
                        endpoint.sampleRequest = tagObj
                    else if (tagObj.tag === 'apiParam')
                        endpoint.params.push(tagObj)
                    else if (tagObj.tag === 'apiSuccessExample') {
                        endpoint.successExample = tagObj
                        endpoint.successExample.header = tagObj.description.split('\n')[0]

                        var structure = tagObj.description.split('OK')[1];

                        endpoint.successExample.structure = syntaxHighlight(JSON.stringify(
                            JSON.parse( tagObj.description.split('OK')[1] ), null, 2)
                        ) ;
                    }

                    //apiSuccess
                }

                api.push(endpoint)
            }

            console.log('api',  api)

            $s.api = api;
        })

    function syntaxHighlight(json) {
        json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
        return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
            var cls = 'number';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'key';
                } else {
                    cls = 'string';
                }
            } else if (/true|false/.test(match)) {
                cls = 'boolean';
            } else if (/null/.test(match)) {
                cls = 'null';
            }
            return '' + match + '';
        });
    }
}])

.controller('UserStatus',
['$scope', '$stateParams', 'Auth',
function($s, $stateParams, auth) {
    console.log('user status controller')

    // join room user-status
    var socket = io.connect('http://0.0.0.0:3000/user-status');

    console.log('auth.token', auth.token)

    socket.on('connect', function() {

        // initial request for meta data
        socket.emit('request meta', function(meta) {
            //console.log('data', meta)

            $s.$apply(function() {
                $s.meta = meta;
            })
        })

        // subsequent count updates
        socket.on('update meta', function(meta) {
            //console.log('trying to update to meta', meta)
            $s.$apply(function() {
                $s.meta = meta;
            })
        })
    })
}])

.controller('Proto',
['$scope', '$stateParams', '$timeout',
function($scope, $stateParams, $timeout) {

}])
<|endoftext|>


<commit_before>// Examples of commonly used models

Model.Primitive = Model([Boolean, Number, String, Symbol]);

// Booleans-like
Model.Falsy = Model([Model.Primitive, null, undefined]).assert(function isFalsy(val){ return !val });
Model.Truthy = Model([Model.Primitive, Object]).assert(function isTruthy(val){ return !!val });

// Numbers
Model.Integer = Model(Number).assert(Number.isInteger);
Model.SafeInteger = Model(Number).assert(Number.isSafeInteger);
Model.FiniteNumber = Model(Number).assert(Number.isFinite);
Model.PositiveNumber = Model(Number).assert(function isPositive(val){ return val >= 0 });
Model.NegativeNumber = Model(Number).assert(function isNegative(val){ return val <= 0 });
Model.PositiveInteger = Model.PositiveNumber.extend().assert(Number.isInteger);
Model.NegativeInteger = Model.NegativeNumber.extend().assert(Number.isInteger);

// Strings
Model.StringNotBlank = Model(String).assert(function isNotBlank(str){ return str.trim().length > 0 });
Model.NormalizedString = Model(String).assert(function isNormalized(str){ return str.normalize() === str });
Model.TrimmedString = Model(String).assert(function isTrimmed(str){ return str.trim() === str });

// Dates
Model.PastDate = Model(Date).assert(function isInThePast(date){ return date.getTime() < Date.now() });
Model.FutureDate = Model(Date).assert(function isInTheFuture(date){ return date.getTime() > Date.now() });

// Arrays
Model.ArrayNotEmpty = Model(Array).assert(function isNotEmpty(arr){ return arr.length > 0 });
Model.ArrayUnique = Model(Array).assert(function hasNoDuplicates(arr){
	return arr.every(function(val, idx){
		return arr.indexOf(val) === idx
	})
});
Model.ArrayDense = Model(Array).assert(function hasNoHoles(arr){
	return arr.filter(function(x){ return true }).length === arr.length
});<commit_msg>added ES6 import in examples<commit_after>// Examples of commonly used models
import Model from "objectmodel"

Model.Primitive = Model([Boolean, Number, String, Symbol]);

// Booleans-like
Model.Falsy = Model([Model.Primitive, null, undefined]).assert(function isFalsy(val){ return !val });
Model.Truthy = Model([Model.Primitive, Object]).assert(function isTruthy(val){ return !!val });

// Numbers
Model.Integer = Model(Number).assert(Number.isInteger);
Model.SafeInteger = Model(Number).assert(Number.isSafeInteger);
Model.FiniteNumber = Model(Number).assert(Number.isFinite);
Model.PositiveNumber = Model(Number).assert(function isPositive(val){ return val >= 0 });
Model.NegativeNumber = Model(Number).assert(function isNegative(val){ return val <= 0 });
Model.PositiveInteger = Model.PositiveNumber.extend().assert(Number.isInteger);
Model.NegativeInteger = Model.NegativeNumber.extend().assert(Number.isInteger);

// Strings
Model.StringNotBlank = Model(String).assert(function isNotBlank(str){ return str.trim().length > 0 });
Model.NormalizedString = Model(String).assert(function isNormalized(str){ return str.normalize() === str });
Model.TrimmedString = Model(String).assert(function isTrimmed(str){ return str.trim() === str });

// Dates
Model.PastDate = Model(Date).assert(function isInThePast(date){ return date.getTime() < Date.now() });
Model.FutureDate = Model(Date).assert(function isInTheFuture(date){ return date.getTime() > Date.now() });

// Arrays
Model.ArrayNotEmpty = Model(Array).assert(function isNotEmpty(arr){ return arr.length > 0 });
Model.ArrayUnique = Model(Array).assert(function hasNoDuplicates(arr){
	return arr.every(function(val, idx){
		return arr.indexOf(val) === idx
	})
});
Model.ArrayDense = Model(Array).assert(function hasNoHoles(arr){
	return arr.filter(function(x){ return true }).length === arr.length
});<|endoftext|>


<commit_before>'use strict';
require('babel-polyfill')

var utils = require('./utils');
var state = require('./SelectState')
var selectEvent = require('./selectEvent')

var DEFAULT_CONFIG = {};

function Edt(config) {
  this.el = config.el;
  this.sl = window.getSelection();
  this.callbackInChange = (s) => {
    console.log('default callbackInChange');
  };
  this.slState = new state().export();
}

Edt.prototype.addCallback = function(cb){
  this.callbackInChange=cb;
}

const createInstance = config => new Edt(config);

const SQEdt=(el,option)=>{
  if (!el) {
    throw new Error('element must be prepared!')
  }

  let edt = createInstance(Object.assign({
    el: el
  }, option, DEFAULT_CONFIG));

  //when a para is empty, cell will be replace with this
  el.addEventListener('keyup', e => {
    let sl = window.getSelection();
    if (e.keyCode === 8) {
      if (sl.isCollapsed) {
        let para = utils.getParent(sl.anchorNode, '.para');
        if (para && para.innerHTML === '
') {
          para.innerHTML = '
';
          sl.getRangeAt(0).selectNode(para.firstElementChild)
        }
      }
      if(el.innerHTML === ''){
        el.innerHTML = '

'
      }
    }
  })

  //add selectionchange to inform UI
  document.addEventListener('selectionchange', e => {
    if (document.activeElement === el) { //judge the cursor in the el
      let state = selectEvent(window.getSelection());
      let same = utils.isEqual(edt.slState, state);
      console.log(same);
      console.log(state.toString());
      console.log(edt.slState.toString());
      if (!same) {
        edt.slState = state;
        edt.callbackInChange(state, e); //call the callback to subscriber
      }
    }
  })

  //cause of the function not fully prepared
  el.addEventListener('copy', e => {
    e.returnValue = false;
    return false;
  })

  el.addEventListener('paste', e => {
    e.returnValue = false;
    return false;
  })

  el.addEventListener('cut', e => {
    e.returnValue = false;
    return false;
  })

  el.contentEditable =true;

  el.style.textAlign = 'left';

  return edt;
}

module.exports = SQEdt;
<commit_msg>prevent default command(cmd+i/cmd+b)<commit_after>'use strict';
require('babel-polyfill')

var utils = require('./utils');
var state = require('./SelectState')
var selectEvent = require('./selectEvent')

var DEFAULT_CONFIG = {};

function Edt(config) {
  this.el = config.el;
  this.sl = window.getSelection();
  this.callbackInChange = (s) => {
    console.log('default callbackInChange');
  };
  this.slState = new state().export();
}

Edt.prototype.addCallback = function(cb){
  this.callbackInChange=cb;
}

const createInstance = config => new Edt(config);

const SQEdt=(el,option)=>{
  if (!el) {
    throw new Error('element must be prepared!')
  }

  let edt = createInstance(Object.assign({
    el: el
  }, option, DEFAULT_CONFIG));

  //when a para is empty, cell will be replace with this
  el.addEventListener('keyup', e => {
    let sl = window.getSelection();
    if (e.keyCode === 8) {
      if (sl.isCollapsed) {
        let para = utils.getParent(sl.anchorNode, '.para');
        if (para && para.innerHTML === '
') {
          para.innerHTML = '
';
          sl.getRangeAt(0).selectNode(para.firstElementChild)
        }
      }
      if(el.innerHTML === ''){
        el.innerHTML = '

'
      }
    }
  })

  //add selectionchange to inform UI
  document.addEventListener('selectionchange', e => {
    if (document.activeElement === el) { //judge the cursor in the el
      let state = selectEvent(window.getSelection());
      let same = utils.isEqual(edt.slState, state);
      console.log(same);
      console.log(state.toString());
      console.log(edt.slState.toString());
      if (!same) {
        edt.slState = state;
        edt.callbackInChange(state, e); //call the callback to subscriber
      }
    }
  })

  //cause of the function not fully prepared
  // el.addEventListener('copy', e => {
  //   e.returnValue = false;
  //   return false;
  // })

  el.addEventListener('paste', e => {
    e.returnValue = false;
    return false;
  })

  // el.addEventListener('cut', e => {
  //   e.returnValue = false;
  //   return false;
  // })

  el.addEventListener('keydown',e=>{
    console.log(e);
    //cmd+i||cmd+b
    if(e.keyCode==73&&e.metaKey){
      e.returnValue=false;
    }
  })

  el.contentEditable =true;

  el.style.textAlign = 'left';

  return edt;
}

module.exports = SQEdt;
<|endoftext|>


<commit_before> (function (w, undefined) {
     /* global log4javascript */
     if (!w) {
         return false;
     }

     var d = w.document;

     // 'production' or 'development' or 'test' or 'default'
     var ENV = 'production';
     var log4js = log4javascript;
     var defaultLogLevel = log4js.Level.ALL;
     switch (ENV) {
     case 'production':
         defaultLogLevel = log4js.Level.ERROR;
         break;
     case 'test':
         defaultLogLevel = log4js.Level.OFF;
         break;
     case 'development':
         defaultLogLevel = log4js.Level.DEBUG;
     default:
         defaultLogLevel = log4js.Level.ALL;
     }
     var consoleAppender = new log4js.BrowserConsoleAppender();

     /**
      * Create a logger
      * @param  {String} name  Name of the logger
      * @param  {log4javascript.Level} level Level threshold for logging
      * @return {log4javascript.Logger}       A Logger object
      */
     function createLogger(name, level) {
         var logger = log4js.getLogger(name);
         level = level || defaultLogLevel;
         logger.setLevel(level);
         logger.addAppender(consoleAppender);
         return logger;
     }

     var logger = createLogger();
     var genPatternLogger = createLogger('getPattern');
     var randomizeLogger = createLogger('randomize', log4js.Level.OFF);
     var genRandomColorLogger = createLogger('genRandomColor', log4js.Level.OFF);
     var getPatternContainersLogger = createLogger('getPatternContainers');
     var addPatternLogger = createLogger('addPattern');
     var createPatternLogger = createLogger('createPattern');
     var getDataAttribsLogger = createLogger('getDataAttribs');

     function genColorPattern(numberOfColors, colorType) {
         var pattern = [],
             contrast = false;
         colorType = (colorType || '').trim().toUpperCase();
         switch (colorType) {
             case 'DARK':
             case 'LIGHT':
                contrast = false;
                break;
             case 'MIXED':
             default:
                 contrast = true;
         }
         while (numberOfColors--) {
             if (contrast) {
                 colorType = colorType === 'DARK' ? 'LIGHT' : 'DARK';
             }
             pattern.push(genRandomColor(colorType));
         }

         genPatternLogger.debug('Generated Color Pattern:', pattern);
         return pattern;
     }

     /**
      * Create a randome number between min (inclusive) and max (inclusive) value.
      * @param  {Number} min The minimum value (inclusive)
      * @param  {Number} max The maximum value (inclusive)
      * @return {Number}     Number between min and max
      */
     function randomize(min, max) {
         min = min || 0;
         max = max || 255;
         var rand = Math.floor(Math.random() * (max - min + 1)) + min;
         randomizeLogger.debug('Random Number:', rand);
         return rand;
     }

     /**
      * Generate random color.
      *
      * @return {Array} Generated RGB color array
      */
     function genRandomColor(colorType) {

         var min = 0,
             max = 255;
         colorType = (colorType || '').trim().toUpperCase();
         switch (colorType) {
         case 'DARK':
             min = 0;
             max = Math.floor(256 / 2);
             break;
         case 'MEDIUM':
             min = Math.floor(256 / 4);
             max = Math.floor(256 * 3 / 4);
             break;
         case 'LIGHT':
             min = Math.floor(256 / 2);
             max = 255;
         }

         var red = randomize(min, max),
             green = randomize(min, max),
             blue = randomize(min, max);

         var color = [red, green, blue];
         genRandomColorLogger.debug('Random Color:', color);
         return color;
     }

     /**
      * Find all pattern containers
      * @return {NodeList} All pattern containers
      */
     function getPatternContainers() {
         // All pattern containers (in NodeList)
         var patternContainers = d.querySelectorAll('[data-pattern].pattern');

         getPatternContainersLogger.debug('All Pattern Containers:', patternContainers);
         return patternContainers;
     }

     /**
      * Get data attributes with the "prefix"
      * @param  {NodeElement} element Element from which to get the data- attribute values
      * @param  {String} prefix    The prefix to look for
      * @return {Object}           A data object containing the data attribute property names and values
      */
     function getDataAttribs(element, prefix) {
         var data = {};
         if (!element.hasAttributes()) {
             return data;
         }
         var attribs = [].slice.apply(element.attributes);

         var dataPrefixRegex = new RegExp('^data-' + prefix + '-?', 'i');
         var dataPrefixAttribs = attribs.filter(function (attrib) {
             return dataPrefixRegex.test(attrib.name);
         });

         // No data-prefix is found
         if (dataPrefixAttribs.length === 0) {
             return data;
         }

         getDataAttribsLogger.debug('dataPrefixAttribs:', dataPrefixAttribs);
         // TODO: fill the data object with property names and values
         dataPrefixAttribs.forEach(function (attrib) {
             // remove the data- prefix from attribute name
             var name = attrib.name.replace(/^data-/i, '').toLowerCase();
             data[name] = attrib.value;
         });

         getDataAttribsLogger.debug('Data:', data);
         return data;
     }

     /**
      * Add a pattern inside the pattern container.
      */
     function addPattern() {
         var patternContainers = [].slice.apply(getPatternContainers());
         patternContainers.forEach(function (container) {
             addPatternLogger.debug('Pattern Container:', container);

             // pre-fill default options
             var options = {
                 'pattern': 10,
                 'pattern-width': 10,
                 'pattern-animation': 'outiside-in',
                 'pattern-controller': 'default',
                 'pattern-contrast': ''
             };
             options_ = getDataAttribs(container, 'pattern');
             Object.keys(options_).forEach(function (key) {
                 options[key] = options_[key];
             });
             // TODO: Add additional options

             // TODO: generate pattern
             var colorPattern = genColorPattern(options.pattern, options['pattern-contrast']);
             var patternFragment = createPattern(colorPattern, options, container);
             container.appendChild(patternFragment);
         });
     }

     /**
      * Convert rgb color value to hex value
      * @param  {Array} rgb Array of red, green and blue value
      * @return {String}     Hex value
      */
     function rgbToHex(rgb) {
         var rgbToHexLogger = createLogger('rgbToHex');
         var hex = '#';

         var red = rgb[0];
         var green = rgb[1];
         var blue = rgb[2];

         // TODO: Convert rgb to hex

         rgbToHexLogger.debug('HEX:', hex);
         return hex;
     }

     function rgbString(rgb) {
         return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
     }

     /**
      * Create pattern DOM elements
      * @param  {Array} colorPattern A set of color patterns to use
      * @param  {Object} options      Options object containing configuration options to create the pattern
      * @return {DocumentFragment}              The document fragment object in which the pattern elements are created
      */
     function createPattern(colorPattern, options, container) {
         var patternFragment = d.createDocumentFragment();
         // TODO: Create and Append all pattern divs to patternFragment
         var nPatterns = Number(options.pattern);
         // FIXME:
         var containerWidth = container.offsetWidth;
         var containerHeight = container.offsetHeight;
         var width = containerWidth,
             height = containerHeight,
             top = 0,
             left = 0;
         for (var i = 0; i < nPatterns; i++) {
             if (i % 2 === 0) { // even
                 div = d.createElement('div');
                 div.style.backgroundColor = rgbString(colorPattern[i]);
                 div.style.width = width + 'px';
                 div.style.height = height + 'px';
                 div.style.top = top + 'px';
                 div.style.left = left + 'px';
                 patternFragment.appendChild(div);
             }
             else { // odd
                 div.style.border = options['pattern-width'] + 'px' + ' solid ' + rgbString(colorPattern[i]);
             }

             width -= 2 * options['pattern-width'];
             height = width;
             top += options['pattern-width'];
             left = top;
         }

         createPatternLogger.debug(patternFragment);
         return patternFragment;
     }

     function init() {
         logger.info('Pattern.js Library Initiated');
         addPattern();

         return true;
     }

     return init();
 })(this.window);
<commit_msg>Fix development log level<commit_after> (function (w, undefined) {
     /* global log4javascript */
     if (!w) {
         return false;
     }

     var d = w.document;

     // 'production' or 'development' or 'test' or 'default'
     var ENV = 'production';
     var log4js = log4javascript;
     var defaultLogLevel = log4js.Level.ALL;
     switch (ENV) {
     case 'production':
         defaultLogLevel = log4js.Level.ERROR;
         break;
     case 'test':
         defaultLogLevel = log4js.Level.OFF;
         break;
     case 'development':
         defaultLogLevel = log4js.Level.DEBUG;
         break;
     default:
         defaultLogLevel = log4js.Level.ALL;
     }
     var consoleAppender = new log4js.BrowserConsoleAppender();

     /**
      * Create a logger
      * @param  {String} name  Name of the logger
      * @param  {log4javascript.Level} level Level threshold for logging
      * @return {log4javascript.Logger}       A Logger object
      */
     function createLogger(name, level) {
         var logger = log4js.getLogger(name);
         level = level || defaultLogLevel;
         logger.setLevel(level);
         logger.addAppender(consoleAppender);
         return logger;
     }

     var logger = createLogger();
     var genPatternLogger = createLogger('getPattern');
     var randomizeLogger = createLogger('randomize', log4js.Level.OFF);
     var genRandomColorLogger = createLogger('genRandomColor', log4js.Level.OFF);
     var getPatternContainersLogger = createLogger('getPatternContainers');
     var addPatternLogger = createLogger('addPattern');
     var createPatternLogger = createLogger('createPattern');
     var getDataAttribsLogger = createLogger('getDataAttribs');

     function genColorPattern(numberOfColors, colorType) {
         var pattern = [],
             contrast = false;
         colorType = (colorType || '').trim().toUpperCase();
         switch (colorType) {
             case 'DARK':
             case 'LIGHT':
                contrast = false;
                break;
             case 'MIXED':
             default:
                 contrast = true;
         }
         while (numberOfColors--) {
             if (contrast) {
                 colorType = colorType === 'DARK' ? 'LIGHT' : 'DARK';
             }
             pattern.push(genRandomColor(colorType));
         }

         genPatternLogger.debug('Generated Color Pattern:', pattern);
         return pattern;
     }

     /**
      * Create a randome number between min (inclusive) and max (inclusive) value.
      * @param  {Number} min The minimum value (inclusive)
      * @param  {Number} max The maximum value (inclusive)
      * @return {Number}     Number between min and max
      */
     function randomize(min, max) {
         min = min || 0;
         max = max || 255;
         var rand = Math.floor(Math.random() * (max - min + 1)) + min;
         randomizeLogger.debug('Random Number:', rand);
         return rand;
     }

     /**
      * Generate random color.
      *
      * @return {Array} Generated RGB color array
      */
     function genRandomColor(colorType) {

         var min = 0,
             max = 255;
         colorType = (colorType || '').trim().toUpperCase();
         switch (colorType) {
         case 'DARK':
             min = 0;
             max = Math.floor(256 / 2);
             break;
         case 'MEDIUM':
             min = Math.floor(256 / 4);
             max = Math.floor(256 * 3 / 4);
             break;
         case 'LIGHT':
             min = Math.floor(256 / 2);
             max = 255;
         }

         var red = randomize(min, max),
             green = randomize(min, max),
             blue = randomize(min, max);

         var color = [red, green, blue];
         genRandomColorLogger.debug('Random Color:', color);
         return color;
     }

     /**
      * Find all pattern containers
      * @return {NodeList} All pattern containers
      */
     function getPatternContainers() {
         // All pattern containers (in NodeList)
         var patternContainers = d.querySelectorAll('[data-pattern].pattern');

         getPatternContainersLogger.debug('All Pattern Containers:', patternContainers);
         return patternContainers;
     }

     /**
      * Get data attributes with the "prefix"
      * @param  {NodeElement} element Element from which to get the data- attribute values
      * @param  {String} prefix    The prefix to look for
      * @return {Object}           A data object containing the data attribute property names and values
      */
     function getDataAttribs(element, prefix) {
         var data = {};
         if (!element.hasAttributes()) {
             return data;
         }
         var attribs = [].slice.apply(element.attributes);

         var dataPrefixRegex = new RegExp('^data-' + prefix + '-?', 'i');
         var dataPrefixAttribs = attribs.filter(function (attrib) {
             return dataPrefixRegex.test(attrib.name);
         });

         // No data-prefix is found
         if (dataPrefixAttribs.length === 0) {
             return data;
         }

         getDataAttribsLogger.debug('dataPrefixAttribs:', dataPrefixAttribs);
         // TODO: fill the data object with property names and values
         dataPrefixAttribs.forEach(function (attrib) {
             // remove the data- prefix from attribute name
             var name = attrib.name.replace(/^data-/i, '').toLowerCase();
             data[name] = attrib.value;
         });

         getDataAttribsLogger.debug('Data:', data);
         return data;
     }

     /**
      * Add a pattern inside the pattern container.
      */
     function addPattern() {
         var patternContainers = [].slice.apply(getPatternContainers());
         patternContainers.forEach(function (container) {
             addPatternLogger.debug('Pattern Container:', container);

             // pre-fill default options
             var options = {
                 'pattern': 10,
                 'pattern-width': 10,
                 'pattern-animation': 'outiside-in',
                 'pattern-controller': 'default',
                 'pattern-contrast': ''
             };
             options_ = getDataAttribs(container, 'pattern');
             Object.keys(options_).forEach(function (key) {
                 options[key] = options_[key];
             });
             // TODO: Add additional options

             // TODO: generate pattern
             var colorPattern = genColorPattern(options.pattern, options['pattern-contrast']);
             var patternFragment = createPattern(colorPattern, options, container);
             container.appendChild(patternFragment);
         });
     }

     /**
      * Convert rgb color value to hex value
      * @param  {Array} rgb Array of red, green and blue value
      * @return {String}     Hex value
      */
     function rgbToHex(rgb) {
         var rgbToHexLogger = createLogger('rgbToHex');
         var hex = '#';

         var red = rgb[0];
         var green = rgb[1];
         var blue = rgb[2];

         // TODO: Convert rgb to hex

         rgbToHexLogger.debug('HEX:', hex);
         return hex;
     }

     function rgbString(rgb) {
         return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
     }

     /**
      * Create pattern DOM elements
      * @param  {Array} colorPattern A set of color patterns to use
      * @param  {Object} options      Options object containing configuration options to create the pattern
      * @return {DocumentFragment}              The document fragment object in which the pattern elements are created
      */
     function createPattern(colorPattern, options, container) {
         var patternFragment = d.createDocumentFragment();
         // TODO: Create and Append all pattern divs to patternFragment
         var nPatterns = Number(options.pattern);
         // FIXME:
         var containerWidth = container.offsetWidth;
         var containerHeight = container.offsetHeight;
         var width = containerWidth,
             height = containerHeight,
             top = 0,
             left = 0;
         for (var i = 0; i < nPatterns; i++) {
             if (i % 2 === 0) { // even
                 div = d.createElement('div');
                 div.style.backgroundColor = rgbString(colorPattern[i]);
                 div.style.width = width + 'px';
                 div.style.height = height + 'px';
                 div.style.top = top + 'px';
                 div.style.left = left + 'px';
                 patternFragment.appendChild(div);
             }
             else { // odd
                 div.style.border = options['pattern-width'] + 'px' + ' solid ' + rgbString(colorPattern[i]);
             }

             width -= 2 * options['pattern-width'];
             height = width;
             top += options['pattern-width'];
             left = top;
         }

         createPatternLogger.debug(patternFragment);
         return patternFragment;
     }

     function init() {
         logger.info('Pattern.js Library Initiated');
         addPattern();

         return true;
     }

     return init();
 })(this.window);
<|endoftext|>


<commit_before>(function(global, undef) {
    function isPrimitive(val) {
        return Object(val) !== val;
    }
    function isArrayLike(val) {
        return !isPrimitive(val) &&
            typeof val !== "function" &&
            val.length &&
            val.hasOwnProperty(0);
    }
    function makeArray(val) {
        return isArrayLike(val) ? val : val ? [val] : [];
    }
    function defaultFn() {
        return arguments.length > 1 ? arguments : arguments[0];
    }
    function each(arr, fn) {
        var i, len;
        for (i = 0, len = arr.length; i < len; i += 1) {
            fn(arr[i], i, arr);
        }
    }
    function Stack(fn, next) {
        if (isArrayLike(fn)) {
            var stack;
            each(fn, function (f) {
                stack = stack ? stack.push(f) : new Stack(f);
            });
            return stack;
        }
        if (!(this instanceof Stack)) {
            return new Stack(fn, next);
        }
        this.fn = fn || defaultFn;
        this.next = next || undef;
    }
    Stack.prototype.push = function(fn) {
        return new Stack(fn, this);
    };
    Stack.prototype.unshift = function (fn) {
        return this.next = new Stack(fn, this.next);
    };
    Stack.prototype.concat = function (arr) {
        var prev = this;
        arr.forEach(function (fn) {
            prev = prev.unshift(fn);
        });
        return this;
    };
    Stack.prototype.index = function (idx) {
        return !idx ? this : this.next && this.next.index(idx - 1);
    };
    Stack.prototype.search = function (fn) {
        return (this.fn === fn) ? this : this.next && this.next.search(fn);
    };
    Stack.prototype.call = function (arg, reciever) {
        var val = this.fn.call(reciever || this, arg);
        return this.next ? this.next.call(val, reciever || this) : val;
    };
    Stack.prototype.apply = function (args, reciever) {
        var val = this.fn.apply(reciever|| this, args);
        return this.next ? this.next.apply(makeArray(val), reciever || this) : val;
    };
    Stack.prototype.clone = function (fn, next) {
        return new Stack(fn || this.fn, next || this.next);
    };
    Stack.prototype.remove = function () {
        var removed = this.next;
        this.next = undef;
        return removed;
    };
    Stack.prototype.penultimate = function () {
        var current = this;
        var previous;
        while (current.next) {
            previous = current;
            current = current.next;
        }
        return previous;
    };
    Stack.prototype.shift = function () {
        return this.penultimate().remove();
    };
    Stack.prototype.pop = function () {
        return this.remove();
    };
    global.Stack = Stack;
}(this));
<commit_msg>Update src/stack.js<commit_after>(function(global, undef) {
    function isPrimitive(val) {
        return Object(val) !== val;
    }
    function isArrayLike(val) {
        return !isPrimitive(val) &&
            typeof val !== "function" &&
            val.length &&
            val.hasOwnProperty(0);
    }
    function makeArray(val) {
        return isArrayLike(val) ? val : val ? [val] : [];
    }
    function defaultFn() {
        return arguments.length > 1 ? arguments : arguments[0];
    }
    function each(arr, fn) {
        var i, len;
        for (i = 0, len = arr.length; i < len; i += 1) {
            fn(arr[i], i, arr);
        }
    }
    function Stack(fn, next) {
        if (isArrayLike(fn)) {
            var stack;
            each(fn, function (f) {
                stack = stack ? stack.push(f) : new Stack(f);
            });
            return stack;
        }
        if (!(this instanceof Stack)) {
            return new Stack(fn, next);
        }
        this.fn = fn || defaultFn;
        this.next = next || undef;
    }
    Stack.prototype.push = function(fn) {
        return new Stack(fn, this);
    };
    Stack.prototype.unshift = function (fn) {
        return this.next = new Stack(fn, this.next);
    };
    Stack.prototype.concat = function (arr) {
        var prev = this;
        arr.forEach(function (fn) {
            prev = prev.unshift(fn);
        });
        return this;
    };
    Stack.prototype.index = function (idx) {
        return !idx ? this : this.next && this.next.index(idx - 1);
    };
    Stack.prototype.search = function (fn) {
        return (this.fn === fn) ? this : this.next && this.next.search(fn);
    };
    Stack.prototype.call = function (arg, reciever) {
        var val = this.fn.call(reciever || this, arg);
        return this.next ? this.next.call(val, reciever || this) : val;
    };
    Stack.prototype.apply = function (args, reciever) {
        var val = this.fn.apply(reciever|| this, args);
        return this.next ? this.next.apply(makeArray(val), reciever || this) : val;
    };
    Stack.prototype.clone = function (fn, next) {
        return new Stack(fn || this.fn, next || this.next);
    };
    Stack.prototype.shift = function () {
        var removed = this.next;
        this.next = undef;
        return removed;
    };
    Stack.prototype.penultimate = function () {
        var current = this;
        var previous;
        while (current.next) {
            previous = current;
            current = current.next;
        }
        return previous;
    };
    Stack.prototype.shift = function () {
        return this.penultimate().shift();
    };
    Stack.prototype.pop = function () {
        return this.shift();
    };
    global.Stack = Stack;
}(this));
<|endoftext|>


<commit_before>var Trybutton = React.createClass({
  render: function(){
    return (

         TRY FIRST.

    );
  }
});
var Answerbutton = React.createClass({
  render: function(){
    return (

         SAMPLE ANSWER.

    );
  }
});
var Rbutton =React.createClass({
  render: function(){
    return (

        <Trybutton tryurl={this.props.tryurl}/>
        <Answerbutton ansurl={this.pros.ansurl}/>

    );
  }
});

var makerbutton=function(urls){
  for(var i=0; i<urls.length;i++){
    var tryurl="http://runnable.com/"+urls[i].try;
    console.log("try:"+tryurl);
    var ansurl="http://runnable.com/"+urls[i].ans;
    console.log("ans:"+ansurl);
    var mybutton=<Rbutton tryurl={tryurl } ansurl={ansurl} />;
    React.render(mybutton,document.getElementById(urls[i].id));
  }
}

<commit_msg>Update rbutton.js<commit_after>var Trybutton = React.createClass({
  render: function(){
    return (

         TRY FIRST.

    );
  }
});
var Answerbutton = React.createClass({
  render: function(){
    return (

         SAMPLE ANSWER.

    );
  }
});
var Rbutton =React.createClass({
  render: function(){
    return (

        <Trybutton tryurl={this.props.tryurl}/>
        <Answerbutton ansurl={this.props.ansurl}/>

    );
  }
});

var makerbutton=function(urls){
  for(var i=0; i<urls.length;i++){
    var tryurl="http://runnable.com/"+urls[i].try;
    console.log("try:"+tryurl);
    var ansurl="http://runnable.com/"+urls[i].ans;
    console.log("ans:"+ansurl);
    var mybutton=<Rbutton tryurl={tryurl } ansurl={ansurl} />;
    React.render(mybutton,document.getElementById(urls[i].id));
  }
}

<|endoftext|>


<commit_before>function removeParent(elt) {
    $(elt).parent().remove();
}

function makeDeleteButton() {
    return '<button class="delete" onclick="removeParent(this)">-</button>';
}

function insertRoute(val) {
    $(val).parent().after(makeRoute(''));
}

function makeRoute(val) {
    return ' <input type="text" class="route" value="' + val + '" onkeyup="updateUrl()" >' +
        makeDeleteButton() + ' ' +
        '<button class="add" onclick="insertRoute(this)">+</button>';
}

function makeParam(key, val) {
    return ' <input type="text" class="key" value="' + key + '" onkeyup="updateUrl()" />=' +
        '<input class="value" value="' + val + '" onkeyup="updateUrl()" />' +
        makeDeleteButton() + ''
}

function insertParam() {
    $("#parameterList").append(makeParam('', ''));
}

function finalUrl() {
    var finalUrl = $('#api input.api').val();

    $("#route input.route").each(function(){
        finalUrl += '/' + this.value;
    });

    finalUrl += '?';

    $('#parameters input.key, #parameters input.value').each(function(){
        finalUrl += this.value;
        if (this.className == 'key') {
            finalUrl += '=';
        } if (this.className == 'value') {
            finalUrl += '&';
        }
    });
    return finalUrl;
}

function submit() {
    var token = $('#token input.token').val();
    var f = finalUrl();
    window.location = '?request={0}&token={1}'.format(encodeURIComponent(f),
                                    encodeURIComponent(token));
}

function updateUrl() {
    var f = finalUrl();
    $('#requestUrl').html(finalUrl);
}

$(document).ready(function() {
    var token = $.url("?token");
    if (isUndefined(token)) { token = ''; }
    $("#token input.token").attr('value', token);
    $("#urlFormToken").attr('value', token);

    var request = $.url("?request");
    if (isUndefined(request)) { return; }

    var api = request.replace(/^(.*\/\/[^\/]*)\/.*$/g, "$1");
    var path = $.url('path', request);
    var routes = isUndefined(path) ? [] : $.url('path', request).split('/');
    var vxxFound = false;
    routes.forEach(function(r) {
      if (!r) { return; }
      if (vxxFound) {
        $("#route").append(makeRoute(r));
      } else {
        api = api + '/' + r;
        vxxFound = /^v\d+$/.test(r);
      }
    })
    $("#api input.api").attr('value', api);

    var params = $.url("?", request);
    if (! isUndefined(params)) {
        var param_elt = $("#parameterList");
        for (var key in params) {
            param_elt.append(makeParam(key, params[key]));
        }
    }
    $('#requestUrl').html(request);
});
<commit_msg>encode and decode request<commit_after>function removeParent(elt) {
    $(elt).parent().remove();
}

function makeDeleteButton() {
    return '<button class="delete" onclick="removeParent(this)">-</button>';
}

function insertRoute(val) {
    $(val).parent().after(makeRoute(''));
}

function makeRoute(val) {
    return ' <input type="text" class="route" value="' + val + '" onkeyup="updateUrl()" >' +
        makeDeleteButton() + ' ' +
        '<button class="add" onclick="insertRoute(this)">+</button>';
}

function makeParam(key, val) {
    return ' <input type="text" class="key" value="' + key + '" onkeyup="updateUrl()" />=' +
        '<input class="value" value="' + val + '" onkeyup="updateUrl()" />' +
        makeDeleteButton() + ''
}

function insertParam() {
    $("#parameterList").append(makeParam('', ''));
}

function finalUrl() {
    var finalUrl = $('#api input.api').val();

    $("#route input.route").each(function(){
        finalUrl += '/' + encodeURIComponent(this.value);
    });

    finalUrl += '?';

    $('#parameters input.key, #parameters input.value').each(function(){
        finalUrl += encodeURIComponent(this.value);
        if (this.className == 'key') {
            finalUrl += '=';
        } if (this.className == 'value') {
            finalUrl += '&';
        }
    });
    return finalUrl;
}

function submit() {
    var token = $('#token input.token').val();
    var f = finalUrl();
    window.location = '?request={0}&token={1}'.format(encodeURIComponent(f),
                                    encodeURIComponent(token));
}

function updateUrl() {
    var f = finalUrl();
    $('#requestUrl').html(finalUrl);
}

$(document).ready(function() {
    var token = $.url("?token");
    if (isUndefined(token)) { token = ''; }
    $("#token input.token").attr('value', token);
    $("#urlFormToken").attr('value', token);

    var request = $.url("?request");
    console.log(request);
    if (isUndefined(request)) { return; }

    var api = request.replace(/^(.*\/\/[^\/]*)\/.*$/g, "$1");
    var path = $.url('path', request);

    var routes = isUndefined(path) ? [] : $.url('path', request).split('/');

    var vxxFound = false;
    routes.forEach(function(r) {
      if (!r) { return; }
      if (vxxFound) {
        $("#route").append(makeRoute(decodeURIComponent(r)));
      } else {
        api = api + '/' + decodeURIComponent(r);
        vxxFound = /^v\d+$/.test(r);
      }
    })
    $("#api input.api").attr('value', api);

    var params = $.url("?", request);
    console.log(params);
    if (! isUndefined(params)) {
        var param_elt = $("#parameterList");
        for (var key in params) {
            param_elt.append(makeParam(decodeURIComponent(key), params[key]));
        }
    }
    $('#requestUrl').html(request);
});
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * A singleton object that contains information about the published simulations.  The specific information contained is
 * that which is needed by Rosetta, the PhET translation utility, to do its job.
 *
 * @author John Blanco
 */

/* eslint-env node */
'use strict';

// imports
const nodeFetch = require( 'node-fetch' ); // eslint-disable-line
const RosettaConstants = require( './RosettaConstants' );
const _ = require( 'underscore' ); // eslint-disable-line
const winston = require( 'winston' );

// constants
const CACHED_DATA_VALID_TIME = 1800; // in seconds

// timestamp when the sim info was last updated, used to determine whether to use cached data
let timeOfLastUpdate = 0;

// sim info object - populated by obtaining metadata from the PhET website, used as a cache, updated when needed
const simInfoObject = {};

// outstanding promise for getting metadata, used to avoid creating duplicate requests if once is already in progress
let inProgressMetadataPromise = null;

// function that updates the local copy of the sim info by retrieving and interpreting metadata from the PhET site
async function updateSimInfo() {
  console.log( 'updateSimInfo called' );
  const url = RosettaConstants.PRODUCTION_SERVER_URL +
              '/services/metadata/1.2/simulations?format=json&type=html&summary';
  const response = await nodeFetch( url );
  const simMetadata = await response.json();
  if ( !simMetadata.projects ) {
    winston.error( 'unable to obtain metadata' );
  }
  else {
    // console.log( 'JSON.stringify( simMetadata ) = ' + JSON.stringify( simMetadata ) );
    simMetadata.projects.forEach( projectInfo => {
      projectInfo.simulations.forEach( simInfo => {
        const simName = simInfo.name;
        const translationLocales = [];
        let englishTitle = '';
        simInfo.localizedSimulations.forEach( localizedSimInfo => {
          translationLocales.push( localizedSimInfo.locale );
          if ( localizedSimInfo.locale === 'en' ) {
            englishTitle = localizedSimInfo.title;
          }
        } );

        simInfoObject[ simName ] = {
          englishTitle: englishTitle,
          testUrl: RosettaConstants.PRODUCTION_SERVER_URL + '/sims/html/' + simName + '/latest/' + simName + '_en.html',
          translationLocales: translationLocales
        };
        // console.log( '--------' );
        // console.log( 'simName = ' + simName );
        // console.log( 'englishTitle = ' + englishTitle );
        // console.log( 'translationLocales = ' + translationLocales );
        // console.log( 'simInfoObject[ simName ].testURL = ' + simInfoObject[ simName ].testUrl );
      } );
    } );
    timeOfLastUpdate = Date.now();
  }
}

// function that updates cached data if it is time to do so
async function checkAndUpdateSimInfo() {

  // if a request is already in progress, return that promise
  if ( inProgressMetadataPromise ) {
    winston.info( 'a request for metadata is in progress, waiting on that promise' );
    await inProgressMetadataPromise;
  }
  else if ( (Date.now() - timeOfLastUpdate) / 1000 > CACHED_DATA_VALID_TIME ) {
    winston.info( 'sim info data was stale, initiating a new request' );
    inProgressMetadataPromise = updateSimInfo();
    await inProgressMetadataPromise;
    inProgressMetadataPromise = null; // clear out the promise when it's done
  }
  else {
    winston.info( 'using cached sim info' );
  }
}

// kick off the initial population of the sim data
checkAndUpdateSimInfo()
  .then( () => { winston.info( 'initial population of simInfo object complete' ); } )
  .catch( ( err ) => winston.info( 'initial population of simInfo object failed, err = ' + err ) );

// exported singleton object
module.exports = {

  getListOfSimNames: async function( includeUnpublished ) {
    await checkAndUpdateSimInfo();
    return _.keys( simInfoObject );
  },

  getTestUrl: async function( simName ) {
    await checkAndUpdateSimInfo();
    if ( !simInfoObject[ simName ] ) {
      winston.error( 'sim not found in metadata, simName = ' + simName );
    }
    return simInfoObject[ simName ].testUrl;
  },

  getEnglishTitle: async function( simName ) {
    await checkAndUpdateSimInfo();
    if ( !simInfoObject[ simName ] ) {
      winston.error( 'sim not found in metadata, simName = ' + simName );
    }
    return simInfoObject[ simName ].englishTitle;
  }
};

<commit_msg>added authentication for metadata request<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * A singleton object that contains information about the published simulations.  The specific information contained is
 * that which is needed by Rosetta, the PhET translation utility, to do its job.
 *
 * @author John Blanco
 */

/* eslint-env node */
'use strict';

// imports
const nodeFetch = require( 'node-fetch' ); // eslint-disable-line
const request = require( 'request' );
const RosettaConstants = require( './RosettaConstants' );
const _ = require( 'underscore' ); // eslint-disable-line
const winston = require( 'winston' );

// constants
const CACHED_DATA_VALID_TIME = 1800; // in seconds

// timestamp when the sim info was last updated, used to determine whether to use cached data
let timeOfLastUpdate = 0;

// sim info object - populated by obtaining metadata from the PhET website, used as a cache, updated when needed
const simInfoObject = {};

// outstanding promise for getting metadata, used to avoid creating duplicate requests if once is already in progress
let inProgressMetadataPromise = null;

// function that updates the local copy of the sim info by retrieving and interpreting metadata from the PhET site
async function updateSimInfo() {
  console.log( 'updateSimInfo called' );
  const url = RosettaConstants.PRODUCTION_SERVER_URL +
              '/services/metadata/1.2/simulations?format=json&type=html&include-unpublished=true&summary';

  //-------------
  let simMetadata;
  try {
    simMetadata = await new Promise( ( resolve, reject ) => {
      request( url, async ( error, response, body ) => {
        try {
          body = JSON.parse( body );
        }
          // the JSON object wasn't formatted right, reject
        catch( e ) {
          reject( e );
        }
        // there was some error in the request, reject
        if ( error ) {
          reject( error );
        }
        // there was an error processing the request
        else if ( body.error ) {
          reject( new Error( body.error ) );
        }
        // it's all good, resolve the promise
        else {
          resolve( body );
        }
      } ).auth( 'token', global.preferences.serverToken, true );
    } );
  }
  catch( err ) {
    winston.error( ' failed, err = ' + err );
    return Promise.reject( err );
    // TODO: test this, make sure it's really what I want to do
  }

  if ( !simMetadata || !simMetadata.projects ) {
    winston.error( 'unable to obtain metadata, sim info not updated' );
  }
  else {
    // console.log( 'JSON.stringify( simMetadata ) = ' + JSON.stringify( simMetadata ) );
    simMetadata.projects.forEach( projectInfo => {
      projectInfo.simulations.forEach( simInfo => {
        const simName = simInfo.name;
        const translationLocales = [];
        let englishTitle = '';
        simInfo.localizedSimulations.forEach( localizedSimInfo => {
          translationLocales.push( localizedSimInfo.locale );
          if ( localizedSimInfo.locale === 'en' ) {
            englishTitle = localizedSimInfo.title;
          }
        } );

        simInfoObject[ simName ] = {
          englishTitle: englishTitle,
          testUrl: RosettaConstants.PRODUCTION_SERVER_URL + '/sims/html/' + simName + '/latest/' + simName + '_en.html',
          translationLocales: translationLocales
        };
        // console.log( '--------' );
        // console.log( 'simName = ' + simName );
        // console.log( 'englishTitle = ' + englishTitle );
        // console.log( 'translationLocales = ' + translationLocales );
        // console.log( 'simInfoObject[ simName ].testURL = ' + simInfoObject[ simName ].testUrl );
      } );
    } );
    timeOfLastUpdate = Date.now();
  }
}

// function that updates cached data if it is time to do so
async function checkAndUpdateSimInfo() {

  // if a request is already in progress, return that promise
  if ( inProgressMetadataPromise ) {
    winston.info( 'a request for metadata is in progress, waiting on that promise' );
    await inProgressMetadataPromise;
  }
  else if ( (Date.now() - timeOfLastUpdate) / 1000 > CACHED_DATA_VALID_TIME ) {
    winston.info( 'sim info data was stale, initiating a new request' );
    inProgressMetadataPromise = updateSimInfo();
    await inProgressMetadataPromise;
    inProgressMetadataPromise = null; // clear out the promise when it's done
  }
  else {
    winston.info( 'using cached sim info' );
  }
}

// kick off the initial population of the sim data
checkAndUpdateSimInfo()
  .then( () => { winston.info( 'initial population of simInfo object complete' ); } )
  .catch( ( err ) => winston.info( 'initial population of simInfo object failed, err = ' + err ) );

// exported singleton object
module.exports = {

  getListOfSimNames: async function( includeUnpublished ) {
    await checkAndUpdateSimInfo();
    return _.keys( simInfoObject );
  },

  getTestUrl: async function( simName ) {
    await checkAndUpdateSimInfo();
    if ( !simInfoObject[ simName ] ) {
      winston.error( 'sim not found in metadata, simName = ' + simName );
    }
    return simInfoObject[ simName ].testUrl;
  },

  getEnglishTitle: async function( simName ) {
    await checkAndUpdateSimInfo();
    if ( !simInfoObject[ simName ] ) {
      winston.error( 'sim not found in metadata, simName = ' + simName );
    }
    return simInfoObject[ simName ].englishTitle;
  }
};

<|endoftext|>


<commit_before>var tag = document.querySelectorAll("a.etiket.kapat");
Array.prototype.forEach.call(tag, function(el, i) {
    var tagSpan = document.createElement("span");
    tagSpan.className += "etiket-kaldir";
    tagSpan.innerHTML = "&times";
    el.appendChild(tagSpan);
    tag[i].addEventListener("click", function() {
        el.remove();
    }, false);
});

$("select.tr-select").each(function() {
    var optionLength = $(this).children("option").length;
    $(this).addClass("gizle").wrap("

").after("

");
    var selectSecili = $(this).next("div.tr-select-secili");
    selectSecili.text($(this).children("option").eq(0).text());
    var list = $("
", {
        "class": "tr-select"
    }).insertAfter(selectSecili);
    for (var i = 0; i < optionLength; i++) {
        $("
", {
            text: $(this).children("option").eq(i).text(),
            rel: $(this).children("option").eq(i).val()
        }).appendTo(list);
    }
    var li = list.children("li");
    selectSecili.click(function(e) {
        e.stopPropagation();
        $("div.selectSecili.aktif").each(function() {
            $(this).removeClass("aktif").next("ul.tr-select").hide();
        });
        $(this).toggleClass("aktif").next("ul.tr-select").toggle();
    });
    li.click(function(e) {
        e.stopPropagation();
        selectSecili.text($(this).text()).removeClass("aktif");
        $(this).val($(this).attr("rel"));
        list.hide();
    });
    $(document).click(function() {
        selectSecili.removeClass("aktif");
        list.hide();
    });
});

$placeholder = ".tr-input,.tr-textarea";
placeholder();

function placeholder() {
    $($placeholder).each(function() {
        var placeholder = $(this).attr("placeholder");
        if (placeholder !== undefined && placeholder !== "") {
            var inputId = $(this).attr("id");
            $("body").find("[for='" + inputId + "']").css({
                "color": "#057970",
                "font-size": ".75em",
                "top": "0"
            });
        }
    });
}

var textarea = document.getElementsByClassName("tr-textarea");
Array.prototype.forEach.call(textarea, function(el) {
    el.addEventListener("keyup", function (e) {
        var lineCount = el.value.split(/\r|\r\n|\n/).length;
        var newHeight = ++lineCount * 1.2;
        el.style.height = (lineCount > 4) ? newHeight.toString() + "em" : "6em";
    }, false);
});

$("nav.mobil li ul, nav.menu li ul").parents("li").addClass("acilir");
$("nav.mobil li.acilir ul").hide();
$("nav.mobil").on("click", "li.acilir>a", function() {
    $(this).parents("li.acilir:first").find("ul:first").slideToggle();
});
$("body").on("click", ".menuac", function() {
    $(this).animate({
        opacity: "0"
    }, 10).parents("body").append("

").find("nav.mobil").scrollTop(0);
    if ($("nav.mobil").hasClass("sag")) {
        $("nav.mobil").animate({
            right: "0"
        });
    }
    else {
        $("nav.mobil").animate({
            left: "0"
        });
    }
});
$("body").on("click", ".tr-karart.menu", function() {
    $(this).remove();
    $(".menuac").delay(400).animate({
        opacity: "1"
    }, 250);
    if ($("nav.mobil").hasClass("sag")) {
        $("nav.mobil").animate({
            right: "-250px"
        });
    }
    else {
        $("nav.mobil").animate({
            left: "-250px"
        });
    }
});
$(".tr-tab").each(function(){
    $(this).find(".tab-icerik:not(:first-child)").addClass("gizle")
            .end()
            .find("nav>a:first").addClass("aktif");
});
$(".tr-tab").on("click", "nav>a", function(e) {
    var index = $(this).index();
    $(this).addClass("aktif").siblings().removeClass("aktif")
            .end().closest(".tr-tab")
            .find(".tab-icerikler").children().filter(".tab-icerik").eq(index).removeClass("gizle").siblings().addClass("gizle");
});

$(".tr-filtre [data-source='hepsi'], .filtre-icerik").addClass("aktif");
$(".tr-filtre").on("click", "nav a", function() {
    var source = $(this).data("source");
    $(this).addClass("aktif").siblings().removeClass("aktif").parents(".tr-filtre").find(".filtre-icerik").addClass("aktif").not("[data-target^=" + source + "]").removeClass("aktif");
    if (source == "hepsi" || source == "hepsi aktif") {
        $(this).parents(".tr-filtre").find(".filtre-icerik").addClass("aktif");
    }
})

$(".akordiyon-icerik").hide();
$(".tr-akordiyon > .akordiyon-baslik").on("click", function() {
    var t = $(this);
    var i = t.closest(".tr-akordiyon").children(".akordiyon-baslik").index(t);
    if (t.hasClass("aktif")) {
        t.removeClass("aktif").closest(".tr-akordiyon").children(".akordiyon-icerik").slideUp(250);
    } else {
        t.siblings().removeClass("aktif").end().addClass("aktif").closest(".tr-akordiyon").children(".akordiyon-icerik").eq(i).slideDown(250).siblings(".akordiyon-icerik").slideUp(250);
    }
})
$("body").on("click", "a.modal", function(e) {
    e.preventDefault();
    var href = $(this).attr("href");
    var modal = $("#" + href);
    var overlay = $("

");
    modal.addClass("goster").scrollTop(0);
    if (!$(".tr-karart").length) {
        $("body").append(overlay);
        overlay.animate({opacity: ".5"}, 250);
    }
});
$("body").on("click", "a.kapat,.tr-karart", function(e) {
    e.preventDefault();
    $(".tr-modal").removeClass("goster");
    $.when($(".tr-karart").fadeOut()).done(function() {
        $(".tr-karart").remove();
    });
});
<commit_msg>Placeholder<commit_after>var tag = document.querySelectorAll("a.etiket.kapat");
Array.prototype.forEach.call(tag, function(el, i) {
    var tagSpan = document.createElement("span");
    tagSpan.className += "etiket-kaldir";
    tagSpan.innerHTML = "&times";
    el.appendChild(tagSpan);
    tag[i].addEventListener("click", function() {
        el.remove();
    }, false);
});

$("select.tr-select").each(function() {
    var optionLength = $(this).children("option").length;
    $(this).addClass("gizle").wrap("

").after("

");
    var selectSecili = $(this).next("div.tr-select-secili");
    selectSecili.text($(this).children("option").eq(0).text());
    var list = $("
", {
        "class": "tr-select"
    }).insertAfter(selectSecili);
    for (var i = 0; i < optionLength; i++) {
        $("
", {
            text: $(this).children("option").eq(i).text(),
            rel: $(this).children("option").eq(i).val()
        }).appendTo(list);
    }
    var li = list.children("li");
    selectSecili.click(function(e) {
        e.stopPropagation();
        $("div.selectSecili.aktif").each(function() {
            $(this).removeClass("aktif").next("ul.tr-select").hide();
        });
        $(this).toggleClass("aktif").next("ul.tr-select").toggle();
    });
    li.click(function(e) {
        e.stopPropagation();
        selectSecili.text($(this).text()).removeClass("aktif");
        $(this).val($(this).attr("rel"));
        list.hide();
    });
    $(document).click(function() {
        selectSecili.removeClass("aktif");
        list.hide();
    });
});

var textarea = document.getElementsByClassName("tr-textarea");
Array.prototype.forEach.call(textarea, function(el) {
    el.addEventListener("keyup", function (e) {
        var lineCount = el.value.split(/\r|\r\n|\n/).length;
        var newHeight = ++lineCount * 1.2;
        el.style.height = (lineCount > 4) ? newHeight.toString() + "em" : "6em";
    }, false);
});

$("nav.mobil li ul, nav.menu li ul").parents("li").addClass("acilir");
$("nav.mobil li.acilir ul").hide();
$("nav.mobil").on("click", "li.acilir>a", function() {
    $(this).parents("li.acilir:first").find("ul:first").slideToggle();
});
$("body").on("click", ".menuac", function() {
    $(this).animate({
        opacity: "0"
    }, 10).parents("body").append("

").find("nav.mobil").scrollTop(0);
    if ($("nav.mobil").hasClass("sag")) {
        $("nav.mobil").animate({
            right: "0"
        });
    }
    else {
        $("nav.mobil").animate({
            left: "0"
        });
    }
});
$("body").on("click", ".tr-karart.menu", function() {
    $(this).remove();
    $(".menuac").delay(400).animate({
        opacity: "1"
    }, 250);
    if ($("nav.mobil").hasClass("sag")) {
        $("nav.mobil").animate({
            right: "-250px"
        });
    }
    else {
        $("nav.mobil").animate({
            left: "-250px"
        });
    }
});
$(".tr-tab").each(function(){
    $(this).find(".tab-icerik:not(:first-child)").addClass("gizle")
            .end()
            .find("nav>a:first").addClass("aktif");
});
$(".tr-tab").on("click", "nav>a", function(e) {
    var index = $(this).index();
    $(this).addClass("aktif").siblings().removeClass("aktif")
            .end().closest(".tr-tab")
            .find(".tab-icerikler").children().filter(".tab-icerik").eq(index).removeClass("gizle").siblings().addClass("gizle");
});

$(".tr-filtre [data-source='hepsi'], .filtre-icerik").addClass("aktif");
$(".tr-filtre").on("click", "nav a", function() {
    var source = $(this).data("source");
    $(this).addClass("aktif").siblings().removeClass("aktif").parents(".tr-filtre").find(".filtre-icerik").addClass("aktif").not("[data-target^=" + source + "]").removeClass("aktif");
    if (source == "hepsi" || source == "hepsi aktif") {
        $(this).parents(".tr-filtre").find(".filtre-icerik").addClass("aktif");
    }
})

$(".akordiyon-icerik").hide();
$(".tr-akordiyon > .akordiyon-baslik").on("click", function() {
    var t = $(this);
    var i = t.closest(".tr-akordiyon").children(".akordiyon-baslik").index(t);
    if (t.hasClass("aktif")) {
        t.removeClass("aktif").closest(".tr-akordiyon").children(".akordiyon-icerik").slideUp(250);
    } else {
        t.siblings().removeClass("aktif").end().addClass("aktif").closest(".tr-akordiyon").children(".akordiyon-icerik").eq(i).slideDown(250).siblings(".akordiyon-icerik").slideUp(250);
    }
})
$("body").on("click", "a.modal", function(e) {
    e.preventDefault();
    var href = $(this).attr("href");
    var modal = $("#" + href);
    var overlay = $("

");
    modal.addClass("goster").scrollTop(0);
    if (!$(".tr-karart").length) {
        $("body").append(overlay);
        overlay.animate({opacity: ".5"}, 250);
    }
});
$("body").on("click", "a.kapat,.tr-karart", function(e) {
    e.preventDefault();
    $(".tr-modal").removeClass("goster");
    $.when($(".tr-karart").fadeOut()).done(function() {
        $(".tr-karart").remove();
    });
});
<|endoftext|>


<commit_before>
JET.MaterialLib.missile = new THREE.MeshBasicMaterial({ color: 0x555555 });
JET.MaterialLib.bullet = new THREE.MeshBasicMaterial({ color: 0x111111 });

JET.GeometryLib.missile = new THREE.PlaneGeometry(2, 1);
JET.GeometryLib.bullet = new THREE.PlaneGeometry(1, 1);

/// A projectile
JET.Missile = function(weapon) {
	THREE.Object3D.call(this);
	this.weapon = weapon;
	this.speed = 0;
	this.flightTime = weapon ? weapon.flightTime || 0 : 0;
	this.target = null;
	var geometry = this.weapon.guided ? JET.GeometryLib.missile : JET.GeometryLib.bullet;
	var material = this.weapon.guided ? JET.MaterialLib.missile : JET.MaterialLib.bullet;
	this.mesh = new THREE.Mesh(geometry, material);
	this.add(this.mesh);
};

JET.Missile.prototype = Object.create(THREE.Object3D.prototype);

JET.Missile.prototype.update = function(dt) {
	if (this.flightTime <= 0) return false;
	this.flightTime -= dt;
	var weapon = this.weapon;

	// Homing missiles; there is a small delay before activating
	if (this.target && this.flightTime < weapon.flightTime - 0.2) {
		var desiredAngle = JET.Math.angleBetween(this, this.target);
		var angleError = JET.Math.angleDiff(this.rotation.z, desiredAngle);
		var angleCorr = angleError * 10; // Apply gain
		angleCorr = THREE.Math.clamp(angleCorr, -weapon.turnRate, weapon.turnRate);
		this.rotation.z += angleCorr * dt;
	}
	// Regular movement
	var angle = this.rotation.z;
	var dpos = this.speed * dt;
	this.position.x += Math.cos(angle) * dpos;
	this.position.y += Math.sin(angle) * dpos;

	// Test for hit
	for (var i = 0, l = game.entityCache.length; i < l; ++i) {
		var obj = game.entityCache[i];
		if (obj.id === weapon.ownerId || obj.faction === weapon.faction) continue;
		if (obj.testHit(this.position, weapon.radius)) {
			this.flightTime = 0;
			obj.hull -= weapon.damage;
			addMessage("HIT!");
		}
	}
	return true;
};

/// Weapon capable of shooting projectiles
/// Also manages its projectiles
JET.Weapon = function(name, owner, params) {
	this.name = name;
	this.ownerId = owner.id;
	this.faction = owner.faction;
	this.flightTime = params.flightTime;
	this.damage = params.damage;
	this.ammo = params.ammo;
	this.maxAmmo = params.ammo;
	this.turnRate = params.turnRate || Math.PI / 2;
	this.radius = params.radius || 1;
	this.delay = params.delay || 0.1;
	this.speed = params.speed || 150;
	this.guided  = params.guided || false;
	this.lastTime = 0;
};

JET.Weapon.prototype.shoot = function(shooter) {
	if (this.ammo <= 0) return false;
	var t = Date.now() * 0.001;
	if (t < this.lastTime + this.delay) return false;
	this.lastTime = t;
	--this.ammo;
	var bullet = new JET.Missile(this);
	bullet.position.copy(shooter.position);
	bullet.rotation.copy(shooter.rotation);
	bullet.speed = this.speed + shooter.speed;
	if (this.guided) bullet.target = shooter.target;
	game.addBullet(bullet);
	return true;
};
<commit_msg>Bigger missiles.<commit_after>
JET.MaterialLib.missile = new THREE.MeshBasicMaterial({ color: 0x555555 });
JET.MaterialLib.bullet = new THREE.MeshBasicMaterial({ color: 0x111111 });

JET.GeometryLib.missile = new THREE.PlaneGeometry(3, 1.5);
JET.GeometryLib.bullet = new THREE.PlaneGeometry(1, 1);

/// A projectile
JET.Missile = function(weapon) {
	THREE.Object3D.call(this);
	this.weapon = weapon;
	this.speed = 0;
	this.flightTime = weapon ? weapon.flightTime || 0 : 0;
	this.target = null;
	var geometry = this.weapon.guided ? JET.GeometryLib.missile : JET.GeometryLib.bullet;
	var material = this.weapon.guided ? JET.MaterialLib.missile : JET.MaterialLib.bullet;
	this.mesh = new THREE.Mesh(geometry, material);
	this.add(this.mesh);
};

JET.Missile.prototype = Object.create(THREE.Object3D.prototype);

JET.Missile.prototype.update = function(dt) {
	if (this.flightTime <= 0) return false;
	this.flightTime -= dt;
	var weapon = this.weapon;

	// Homing missiles; there is a small delay before activating
	if (this.target && this.flightTime < weapon.flightTime - 0.2) {
		var desiredAngle = JET.Math.angleBetween(this, this.target);
		var angleError = JET.Math.angleDiff(this.rotation.z, desiredAngle);
		var angleCorr = angleError * 10; // Apply gain
		angleCorr = THREE.Math.clamp(angleCorr, -weapon.turnRate, weapon.turnRate);
		this.rotation.z += angleCorr * dt;
	}
	// Regular movement
	var angle = this.rotation.z;
	var dpos = this.speed * dt;
	this.position.x += Math.cos(angle) * dpos;
	this.position.y += Math.sin(angle) * dpos;

	// Test for hit
	for (var i = 0, l = game.entityCache.length; i < l; ++i) {
		var obj = game.entityCache[i];
		if (obj.id === weapon.ownerId || obj.faction === weapon.faction) continue;
		if (obj.testHit(this.position, weapon.radius)) {
			this.flightTime = 0;
			obj.hull -= weapon.damage;
			addMessage("HIT!");
		}
	}
	return true;
};

/// Weapon capable of shooting projectiles
/// Also manages its projectiles
JET.Weapon = function(name, owner, params) {
	this.name = name;
	this.ownerId = owner.id;
	this.faction = owner.faction;
	this.flightTime = params.flightTime;
	this.damage = params.damage;
	this.ammo = params.ammo;
	this.maxAmmo = params.ammo;
	this.turnRate = params.turnRate || Math.PI / 2;
	this.radius = params.radius || 1;
	this.delay = params.delay || 0.1;
	this.speed = params.speed || 150;
	this.guided  = params.guided || false;
	this.lastTime = 0;
};

JET.Weapon.prototype.shoot = function(shooter) {
	if (this.ammo <= 0) return false;
	var t = Date.now() * 0.001;
	if (t < this.lastTime + this.delay) return false;
	this.lastTime = t;
	--this.ammo;
	var bullet = new JET.Missile(this);
	bullet.position.copy(shooter.position);
	bullet.rotation.copy(shooter.rotation);
	bullet.speed = this.speed + shooter.speed;
	if (this.guided) bullet.target = shooter.target;
	game.addBullet(bullet);
	return true;
};
<|endoftext|>


<commit_before>let skycons = new Skycons({"color": "white"});

function initWeather() {
    let html = '';
    for (var i = 1; i <= 5; i++) {
        let name = "weather-row-" + i + "-";
        html += '
';
        html += '' + name + '	';
        html += '<canvas id="' + (name + "icon-forecast") + '" width="40" height="40"></canvas>	';
        html += '	';
        html += '	';
        html += '
';
    }
    $("#weatherTable").html(html);
}

function updateWeather(location, apiKey) {
    $.simpleWeather({
        location: location,
        apiKey: apiKey,
        unit: 'f',
        success: function (weather) {
            $("#temperature").html(weather.temp + '°' + weather.units.temp.toUpperCase());
            let html = '
' + weather.currently + '
';
            html += '
' + weather.wind.direction + ' ' + weather.wind.speed + ' ' + weather.units.speed + '
';
            html += '
  High ' + weather.high + '  Low ' + weather.low + '
';
            $("#weatherDynamic").html(html);

            for (var i = 1; i <= 5; i++) {
                let name = "weather-row-" + i + "-";
                $("#" + name + "day").text(weather.forecast[i].day + ".");
                $("#" + name + "high").text(weather.forecast[i].high);
                $("#" + name + "low").text(weather.forecast[i].low);
                skycons.set(name + "icon-forecast", weather.forecast[i].icon);
                skycons.play();
            }
            skycons.set("weather-icon", weather.icon);
            skycons.play();
        },
        error: function (error) {
            console.error(error);
            $("#weatherDynamic").html('
' + error + '
');
        }
    });
}
<commit_msg>Don't animate forecast icons to prevent excessive CPU load<commit_after>let skycons = new Skycons({"color": "white"});

function initWeather() {
    let html = '';
    for (var i = 1; i <= 5; i++) {
        let name = "weather-row-" + i + "-";
        html += '
';
        html += '' + name + '	';
        html += '<canvas id="' + (name + "icon-forecast") + '" width="40" height="40"></canvas>	';
        html += '	';
        html += '	';
        html += '
';
    }
    $("#weatherTable").html(html);
}

function updateWeather(location, apiKey) {
    $.simpleWeather({
        location: location,
        apiKey: apiKey,
        unit: 'f',
        success: function (weather) {
            $("#temperature").html(weather.temp + '°' + weather.units.temp.toUpperCase());
            let html = '
' + weather.currently + '
';
            html += '
' + weather.wind.direction + ' ' + weather.wind.speed + ' ' + weather.units.speed + '
';
            html += '
  High ' + weather.high + '  Low ' + weather.low + '
';
            $("#weatherDynamic").html(html);

            for (var i = 1; i <= 5; i++) {
                let name = "weather-row-" + i + "-";
                $("#" + name + "day").text(weather.forecast[i].day + ".");
                $("#" + name + "high").text(weather.forecast[i].high);
                $("#" + name + "low").text(weather.forecast[i].low);
                skycons.set(name + "icon-forecast", weather.forecast[i].icon);
            }
            skycons.set("weather-icon", weather.icon);
            skycons.play();
        },
        error: function (error) {
            console.error(error);
            $("#weatherDynamic").html('
' + error + '
');
        }
    });
}
<|endoftext|>