<commit_before>var app = angular.module('geoChat', ['ui.router', 'ngCookies', 'ngResource', 'ngSanitize','btford.socket-io', 'ngMap'])
    .value('nickName', username);
var username;

app.factory('User', ['$http', function( $http) {
    return {
        addUser: function (user) {
            console.log(user);
            return $http({
                method: 'POST',
                url: '/api/add',
                data:user
            })
                .then(function (resp) {
                    return resp;
                });
        },

        getUser: function(){
            return $http({
                method: 'GET',
                url: '/api/add'
            })
                .then(function (resp) {
                    console.log(resp);
                    return resp.data;
                });
        }
    }
}]);

function statusChangeCallback(response) {
    if (response.status === 'connected') {
        FB.api('/me', function (response) {
            username = response.name;
        });
    }
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

window.fbAsyncInit = function () {
  FB.init({
    appId      : '438180583036734',
    status     : true,
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.2'
  });

  FB.getLoginStatus(function (response) {
    statusChangeCallback(response);
  });

  FB.Event.subscribe('auth.login', function (resp) {
    window.location = 'https://chat-geo.herokuapp.com/#/home';
  });
  FB.Event.subscribe('auth.logout', function (resp) {
    window.location = 'https://chat-geo.herokuapp.com/';
  });
};
// Load the SDK asynchronously
(function (d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {
    return;
  }
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

app.controller('AuthCtrl', ["$scope", "User", function ($scope, User) {
    $scope.username = [];
    $scope.FBLogin = function(){
        FB.login(function(response) {
            if (response.authResponse) {
                console.log('Welcome! Fetching your information... ');
                FB.api('/me', function(response) {
                    console.log('Good to see you, ' + response.name + '.');
                    username = response.name;
                    var accessToken = FB.getAuthResponse().accessToken;
                    console.log(accessToken);
                    $scope.username.push({user:response.name});
                    console.log($scope.username);
                    User.addUser($scope.username)
                        .catch(function (error) {
                            console.log(error);
                        });

                    // User.getUser()
                    //      .then(function (resData){
                    //          console.log(resData[1].user);
                    //          //username = resData[1].user;
                    //     })
                    //     .catch(function (error){
                    //         console.log(error);
                    //     });
                });
            } else {
                console.log('User cancelled login or did not fully authorize.');
            }
        }, {scope: ''});
    };
}]);

app.controller('SocketCtrl', function ($log, $scope, chatSocket, messageFormatter, nickName, $http) {

    $scope.newMessages = [];
    $scope.nickName = username;
    $scope.messageLog = '';

    $scope.FBLogout = function(){
        FB.logout(function(response) {
            console.log("You are logged out");
        });
    };

    $scope.sendMessage = function() {
    var match = $scope.message.match('^\/nick (.*)');

    $log.debug('sending message', $scope.message);
    chatSocket.emit('message', nickName, $scope.message);
    $scope.message = '';
    console.log(username);
  };

  $scope.$on('socket:broadcast', function (event, data) {
    $log.debug('got a message', data);
      console.log("this is sending " + data.source);
    if (!data.payload) {
      $log.error('invalid message', 'event', event, 'data', JSON.stringify(data));
      return;
    }

    $scope.$apply(function() {
      //$scope.messageLog = $scope.messageLog + messageFormatter(new Date(), data.source, data.payload);
        $scope.messageLog = messageFormatter(new Date(), data.source, data.payload);

        $scope.newMessages.push($scope.messageLog);
        console.log(username)

    });
  });
});

//map
app.controller('mapController', function ($scope, $interval, $http, NgMap) {

  var friends = [{ position: {lat: 30.783775, lng: -128.4091839}, marker : new google.maps.Marker() , name: 'RandomGuy'},
    { position: {lat: 33.783775, lng: -120.4091839}, marker : new google.maps.Marker() , name: 'RandomGuy2'},
    { position: {lat: 41.783775, lng: -126.4091839}, marker : new google.maps.Marker() , name: 'RandomGuy3'}
  ];
  var markers = [];
  var me = { position: { }, marker : new google.maps.Marker() };

  var updateMyPosition = function (position) {
    me.position = { lat: position.coords.latitude, lng: position.coords.longitude};
    NgMap.getMap().then(function (map) {
      me.marker.setMap(null);
      me.marker = new google.maps.Marker({
        position: me.position,
        map: map,
        title: username
      })
      map.panTo(me.position);
    });
  };
  navigator.geolocation.getCurrentPosition(updateMyPosition);

  //test
  //friends.push(
  //  {position: new google.maps.LatLng(parseFloat(-70), parseFloat(140)), name: 'Aj'},
  //  {position: new google.maps.LatLng(parseFloat(-34), parseFloat(150)), name: 'Lyly'},
  //  {position: new google.maps.LatLng(parseFloat(0), parseFloat(160)), name: 'Random'}
  //);

  var init = function () {

    //update Positions
    $interval(function () {

      //Send my location and receive other's location
      $http({
        method: 'GET',
        url: 'https://chat-geo.herokuapp.com/location',
        params: {position: me.position, name: username}
      }).then(function successCallback(response) {
         friends = [];
        friends = response.data;

        NgMap.getMap().then(function (map) {

          //delete old markerss
          for(var j = 0 ; j < markers.length; j++){
            markers[j].setMap(null);
          }
          markers.splice(0, markers.length);

          //add new markers
          console.log(friends.length);
          for (var i = 0; i < friends.length; i++) {
            console.log(friends[i].position);
            markers.push(new google.maps.Marker({
              position: friends[i].position,
              map: map,
              title: friends[i].name
            }));
          }
        });
      }, function errorCallback(response) {
        console.log('ajax response failed', response);
      });
    }, 3000);
  };

  init();
});

app.factory('chatSocket', function (socketFactory) {
  var socket = socketFactory();
  socket.forward('broadcast');
  return socket;
});

app.value('messageFormatter', function (date, nick, message) {
  return date.toLocaleTimeString() + ' - ' +
    nick + ' - ' +
    message + '\n';

});

app.config(function ($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');

  $stateProvider
      .state('login', {
        url: '/',
        templateUrl: 'app/auth/login.html',
        controller: 'SocketCtrl'
      });

  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: 'app/chat/chat.html',
      controller: 'SocketCtrl'
    }).state('home.map', {
    url: '/map',
    templateUrl: 'app/map/map.html',
    controller: 'mapController'
  })
});
<commit_msg>adding demo<commit_after>var app = angular.module('geoChat', ['ui.router', 'ngCookies', 'ngResource', 'ngSanitize','btford.socket-io', 'ngMap'])
    .value('nickName', username);
var username;

app.factory('User', ['$http', function( $http) {
    return {
        addUser: function (user) {
            console.log(user);
            return $http({
                method: 'POST',
                url: '/api/add',
                data:user
            })
                .then(function (resp) {
                    return resp;
                });
        },

        getUser: function(){
            return $http({
                method: 'GET',
                url: '/api/add'
            })
                .then(function (resp) {
                    console.log(resp);
                    return resp.data;
                });
        }
    }
}]);

function statusChangeCallback(response) {
    if (response.status === 'connected') {
        FB.api('/me', function (response) {
            username = response.name;
        });
    }
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

window.fbAsyncInit = function () {
  FB.init({
    appId      : '438180583036734',
    status     : true,
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.2'
  });

  FB.getLoginStatus(function (response) {
    statusChangeCallback(response);
  });

  FB.Event.subscribe('auth.login', function (resp) {
    window.location = 'https://chat-geo.herokuapp.com/#/home';
  });
  FB.Event.subscribe('auth.logout', function (resp) {
    window.location = 'https://chat-geo.herokuapp.com/';
  });
};
// Load the SDK asynchronously
(function (d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {
    return;
  }
  js = d.createElement(s);
  js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

app.controller('AuthCtrl', ["$scope", "User", function ($scope, User) {
    $scope.username = [];
    $scope.FBLogin = function(){
        FB.login(function(response) {
            if (response.authResponse) {
                console.log('Welcome! Fetching your information... ');
                FB.api('/me', function(response) {
                    console.log('Good to see you, ' + response.name + '.');
                    username = response.name;
                    var accessToken = FB.getAuthResponse().accessToken;
                    console.log(accessToken);
                    $scope.username.push({user:response.name});
                    console.log($scope.username);
                    User.addUser($scope.username)
                        .catch(function (error) {
                            console.log(error);
                        });
                });
            } else {
                console.log('User cancelled login or did not fully authorize.');
            }
        }, {scope: ''});
    };
}]);

app.controller('SocketCtrl', function ($log, $scope, chatSocket, messageFormatter, nickName, $http) {

    $scope.newMessages = [];
    $scope.nickName = username;
    $scope.messageLog = '';

    $scope.FBLogout = function(){
        FB.logout(function(response) {
            console.log("You are logged out");
        });
    };

    $scope.sendMessage = function() {
    var match = $scope.message.match('^\/nick (.*)');

    $log.debug('sending message', $scope.message);
    chatSocket.emit('message', nickName, $scope.message);
    $scope.message = '';
    console.log(username);
  };

  $scope.$on('socket:broadcast', function (event, data) {
    $log.debug('got a message', data);
      console.log("this is sending " + data.source);
    if (!data.payload) {
      $log.error('invalid message', 'event', event, 'data', JSON.stringify(data));
      return;
    }

    $scope.$apply(function() {
        $scope.messageLog = messageFormatter(new Date(), username, data.payload);

        $scope.newMessages.push($scope.messageLog);
        console.log(username)

    });
  });
});

//map
app.controller('mapController', function ($scope, $interval, $http, NgMap) {

  var friends = [{ position: {lat: 30.783775, lng: -128.4091839}, marker : new google.maps.Marker() , name: 'RandomGuy'},
    { position: {lat: 33.783775, lng: -120.4091839}, marker : new google.maps.Marker() , name: 'RandomGuy2'},
    { position: {lat: 41.783775, lng: -126.4091839}, marker : new google.maps.Marker() , name: 'RandomGuy3'}
  ];
  var markers = [];
  var me = { position: { }, marker : new google.maps.Marker() };

  var updateMyPosition = function (position) {
    me.position = { lat: position.coords.latitude, lng: position.coords.longitude};
    NgMap.getMap().then(function (map) {
      me.marker.setMap(null);
      me.marker = new google.maps.Marker({
        position: me.position,
        map: map,
        title: username
      })
      map.panTo(me.position);
    });
  };
  navigator.geolocation.getCurrentPosition(updateMyPosition);

  //test
  //friends.push(
  //  {position: new google.maps.LatLng(parseFloat(-70), parseFloat(140)), name: 'Aj'},
  //  {position: new google.maps.LatLng(parseFloat(-34), parseFloat(150)), name: 'Lyly'},
  //  {position: new google.maps.LatLng(parseFloat(0), parseFloat(160)), name: 'Random'}
  //);

  var init = function () {

    //update Positions
    $interval(function () {

      //Send my location and receive other's location
      $http({
        method: 'GET',
        url: 'https://chat-geo.herokuapp.com/location',
        params: {position: me.position, name: username}
      }).then(function successCallback(response) {
         friends = [];
        friends = response.data;

        NgMap.getMap().then(function (map) {

          //delete old markerss
          for(var j = 0 ; j < markers.length; j++){
            markers[j].setMap(null);
          }
          markers.splice(0, markers.length);

          //add new markers
          console.log(friends.length);
          for (var i = 0; i < friends.length; i++) {
            console.log(friends[i].position);
            markers.push(new google.maps.Marker({
              position: friends[i].position,
              map: map,
              title: friends[i].name
            }));
          }
        });
      }, function errorCallback(response) {
        console.log('ajax response failed', response);
      });
    }, 3000);
  };

  init();
});

app.factory('chatSocket', function (socketFactory) {
  var socket = socketFactory();
  socket.forward('broadcast');
  return socket;
});

app.value('messageFormatter', function (date, nick, message) {
  return date.toLocaleTimeString() + ' - ' +
    nick + ' - ' +
    message + '\n';

});

app.config(function ($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise('/');

  $stateProvider
      .state('login', {
        url: '/',
        templateUrl: 'app/auth/login.html',
        controller: 'SocketCtrl'
      });

  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: 'app/chat/chat.html',
      controller: 'SocketCtrl'
    }).state('home.map', {
    url: '/map',
    templateUrl: 'app/map/map.html',
    controller: 'mapController'
  })
});
<|endoftext|>


<commit_before>(function() {
  Discourse.Markdown.whiteListIframe(/^(https?:)?\/\/www\.openstreetmap\.org\/export\/embed.html\?.+/i);
})();
<commit_msg>Potential fix for #2<commit_after>(function() {
  if (Discourse.dialect_deprecated) { return; }
  Discourse.Markdown.whiteListIframe(/^(https?:)?\/\/www\.openstreetmap\.org\/export\/embed.html\?.+/i);
})();
<|endoftext|>


<commit_before>var styles = [
    'mixins',

    'bordered-pulled',
    'core',
    'fixed-width',
    'icons',
    'larger',
    'list',
    'path',
    'rotated-flipped',
    'animated',
    'stacked'
];

module.exports = function(content) {
    this.cacheable(true);
    var config = this.exec(content, this.resourcePath);
    var start =
            "@import          \"~font-awesome/less/variables.less\";\n"
            + "@fa-font-path: \"~font-awesome/fonts/\";\n"
            + "@import          \"./font-awesome.config.less\";\n";
    source = start + styles.filter(function(style) {
        return config.styles[style];
    }).map(function(style) {
        return "@import \"~font-awesome/less/" + style + ".less\";";
    }).join("\n");
    return source;
};
<commit_msg>Remove less config hook<commit_after>var styles = [
    'mixins',

    'bordered-pulled',
    'core',
    'fixed-width',
    'icons',
    'larger',
    'list',
    'path',
    'rotated-flipped',
    'animated',
    'stacked'
];

module.exports = function(content) {
    this.cacheable(true);
    var config = this.exec(content, this.resourcePath);
    var start =
            "@import          \"~font-awesome/less/variables.less\";\n"
            + "@fa-font-path: \"~font-awesome/fonts/\";\n";
    source = start + styles.filter(function(style) {
        return config.styles[style];
    }).map(function(style) {
        return "@import \"~font-awesome/less/" + style + ".less\";";
    }).join("\n");
    return source;
};
<|endoftext|>


<commit_before>const zmq = require('zmq');
const router = zmq.socket('router');
const logger = require('./log.js');
const _ = require('underscore');
const EventEmitter = require('events');
const GameRepository = require('./repositories/gameRepository.js');

class GameRouter extends EventEmitter {
    constructor(config) {
        super();

        this.workers = {};
        this.gameRepository = new GameRepository(config.dbPath);

        router.bind(config.mqUrl, err => {
            if(err) {
                logger.info(err);
            }
        });

        router.on('message', this.onMessage.bind(this));

        setInterval(this.checkTimeouts.bind(this), 1000 * 60);
    }

    // External methods
    startGame(game) {
        var node = this.getNextAvailableGameNode();

        if(!node) {
            logger.error('Could not find new node for game');
            return;
        }

        this.gameRepository.create(game.getSaveState());

        node.numGames++;

        this.sendCommand(node.identity, 'STARTGAME', game);
        return node;
    }

    addSpectator(game, user) {
        this.sendCommand(game.node.identity, 'SPECTATOR', { game: game, user: user });
    }

    getNextAvailableGameNode() {
        if(_.isEmpty(this.workers)) {
            return undefined;
        }

        var returnedWorker = undefined;

        _.each(this.workers, worker => {
            if(worker.numGames >= worker.maxGames || worker.disabled) {
                return;
            }

            if(!returnedWorker || returnedWorker.numGames > worker.numGames) {
                returnedWorker = worker;
            }
        });

        return returnedWorker;
    }

    getNodeStatus() {
        return _.map(this.workers, worker => {
            return { name: worker.identity, numGames: worker.numGames, status: worker.disabled ? 'disabled' : 'active' };
        });
    }

    disableNode(nodeName) {
        var worker = this.workers[nodeName];
        if(!worker) {
            return false;
        }

        worker.disabled = true;

        return true;
    }

    enableNode(nodeName) {
        var worker = this.workers[nodeName];
        if(!worker) {
            return false;
        }

        worker.disabled = false;

        return true;
    }

    notifyFailedConnect(game, username) {
        if(!game.node) {
            return;
        }

        this.sendCommand(game.node.identity, 'CONNECTFAILED', { gameId: game.id, username: username });
    }

    closeGame(game) {
        if(!game.node) {
            return;
        }

        this.sendCommand(game.node.identity, 'CLOSEGAME', { gameId: game.id });
    }

    // Events
    onMessage(identity, msg) {
        var identityStr = identity.toString();

        var worker = this.workers[identityStr];

        var message = undefined;

        try {
            message = JSON.parse(msg.toString());
        } catch(err) {
            logger.info(err);
            return;
        }

        switch(message.command) {
            case 'HELLO':
                this.emit('onWorkerStarted', identityStr);
                this.workers[identityStr] = {
                    identity: identityStr,
                    maxGames: message.arg.maxGames,
                    numGames: 0,
                    address: message.arg.address,
                    port: message.arg.port,
                    protocol: message.arg.protocol
                };
                worker = this.workers[identityStr];

                this.emit('onNodeReconnected', identityStr, message.arg.games);

                worker.numGames = _.size(message.arg.games);

                break;
            case 'PONG':
                if(worker) {
                    worker.pingSent = undefined;
                }

                logger.error('PONG received for unknown worker');
                break;
            case 'GAMEWIN':
                this.gameRepository.update(message.arg.game);
                break;
            case 'GAMECLOSED':
                if(worker) {
                    worker.numGames--;
                } else {
                    logger.error('Got close game for non existant worker', identity);
                }

                this.emit('onGameClosed', message.arg.game);

                break;
            case 'PLAYERLEFT':
                if(!message.arg.spectator) {
                    this.gameRepository.update(message.arg.game);
                }

                this.emit('onPlayerLeft', message.arg.gameId, message.arg.player);

                break;
        }

        if(worker) {
            worker.lastMessage = Date.now();
        }
    }

    // Internal methods
    sendCommand(identity, command, arg) {
        router.send([identity, '', JSON.stringify({ command: command, arg: arg })]);
    }

    checkTimeouts() {
        var currentTime = Date.now();
        const pingTimeout = 1 * 60 * 1000;

        _.each(this.workers, worker => {
            if(worker.pingSent && currentTime - worker.pingSent > pingTimeout) {
                logger.info('worker', worker.identity + ' timed out');
                delete this.workers[worker.identity];
                this.emit('onWorkerTimedOut', worker.identity);
            } else if(!worker.pingSent) {
                if(currentTime - worker.lastMessage > pingTimeout) {
                    worker.pingSent = currentTime;
                    this.sendCommand(worker.identity, 'PING');
                }
            }
        });
    }
}

module.exports = GameRouter;
<commit_msg>only log if the worker is actually unknown<commit_after>const zmq = require('zmq');
const router = zmq.socket('router');
const logger = require('./log.js');
const _ = require('underscore');
const EventEmitter = require('events');
const GameRepository = require('./repositories/gameRepository.js');

class GameRouter extends EventEmitter {
    constructor(config) {
        super();

        this.workers = {};
        this.gameRepository = new GameRepository(config.dbPath);

        router.bind(config.mqUrl, err => {
            if(err) {
                logger.info(err);
            }
        });

        router.on('message', this.onMessage.bind(this));

        setInterval(this.checkTimeouts.bind(this), 1000 * 60);
    }

    // External methods
    startGame(game) {
        var node = this.getNextAvailableGameNode();

        if(!node) {
            logger.error('Could not find new node for game');
            return;
        }

        this.gameRepository.create(game.getSaveState());

        node.numGames++;

        this.sendCommand(node.identity, 'STARTGAME', game);
        return node;
    }

    addSpectator(game, user) {
        this.sendCommand(game.node.identity, 'SPECTATOR', { game: game, user: user });
    }

    getNextAvailableGameNode() {
        if(_.isEmpty(this.workers)) {
            return undefined;
        }

        var returnedWorker = undefined;

        _.each(this.workers, worker => {
            if(worker.numGames >= worker.maxGames || worker.disabled) {
                return;
            }

            if(!returnedWorker || returnedWorker.numGames > worker.numGames) {
                returnedWorker = worker;
            }
        });

        return returnedWorker;
    }

    getNodeStatus() {
        return _.map(this.workers, worker => {
            return { name: worker.identity, numGames: worker.numGames, status: worker.disabled ? 'disabled' : 'active' };
        });
    }

    disableNode(nodeName) {
        var worker = this.workers[nodeName];
        if(!worker) {
            return false;
        }

        worker.disabled = true;

        return true;
    }

    enableNode(nodeName) {
        var worker = this.workers[nodeName];
        if(!worker) {
            return false;
        }

        worker.disabled = false;

        return true;
    }

    notifyFailedConnect(game, username) {
        if(!game.node) {
            return;
        }

        this.sendCommand(game.node.identity, 'CONNECTFAILED', { gameId: game.id, username: username });
    }

    closeGame(game) {
        if(!game.node) {
            return;
        }

        this.sendCommand(game.node.identity, 'CLOSEGAME', { gameId: game.id });
    }

    // Events
    onMessage(identity, msg) {
        var identityStr = identity.toString();

        var worker = this.workers[identityStr];

        var message = undefined;

        try {
            message = JSON.parse(msg.toString());
        } catch(err) {
            logger.info(err);
            return;
        }

        switch(message.command) {
            case 'HELLO':
                this.emit('onWorkerStarted', identityStr);
                this.workers[identityStr] = {
                    identity: identityStr,
                    maxGames: message.arg.maxGames,
                    numGames: 0,
                    address: message.arg.address,
                    port: message.arg.port,
                    protocol: message.arg.protocol
                };
                worker = this.workers[identityStr];

                this.emit('onNodeReconnected', identityStr, message.arg.games);

                worker.numGames = _.size(message.arg.games);

                break;
            case 'PONG':
                if(worker) {
                    worker.pingSent = undefined;
                } else {
                    logger.error('PONG received for unknown worker');
                }
                break;
            case 'GAMEWIN':
                this.gameRepository.update(message.arg.game);
                break;
            case 'GAMECLOSED':
                if(worker) {
                    worker.numGames--;
                } else {
                    logger.error('Got close game for non existant worker', identity);
                }

                this.emit('onGameClosed', message.arg.game);

                break;
            case 'PLAYERLEFT':
                if(!message.arg.spectator) {
                    this.gameRepository.update(message.arg.game);
                }

                this.emit('onPlayerLeft', message.arg.gameId, message.arg.player);

                break;
        }

        if(worker) {
            worker.lastMessage = Date.now();
        }
    }

    // Internal methods
    sendCommand(identity, command, arg) {
        router.send([identity, '', JSON.stringify({ command: command, arg: arg })]);
    }

    checkTimeouts() {
        var currentTime = Date.now();
        const pingTimeout = 1 * 60 * 1000;

        _.each(this.workers, worker => {
            if(worker.pingSent && currentTime - worker.pingSent > pingTimeout) {
                logger.info('worker', worker.identity + ' timed out');
                delete this.workers[worker.identity];
                this.emit('onWorkerTimedOut', worker.identity);
            } else if(!worker.pingSent) {
                if(currentTime - worker.lastMessage > pingTimeout) {
                    worker.pingSent = currentTime;
                    this.sendCommand(worker.identity, 'PING');
                }
            }
        });
    }
}

module.exports = GameRouter;
<|endoftext|>


<commit_before>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Darkens a color if it's too light to appear on white
//------------------------------------------------------------------------------
d3plus.color.legible = function(color) {
  var hsl = d3.hsl(color)
  if (hsl.s > .9) hsl.s = .9
  if (hsl.l > .4) hsl.l = .4
  return hsl.toString();
}
<commit_msg>tweaked d3plus.color.legible( ) and made example page<commit_after>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Darkens a color if it's too light to appear on white
//------------------------------------------------------------------------------
d3plus.color.legible = function(color) {

  var hsl = d3.hsl(color)
  if ( hsl.l > .6 ) {
    if ( hsl.s > .8 ) hsl.s = .8
    hsl.l = 0.6
  }
  return hsl.toString()

}
<|endoftext|>


<commit_before>var Record = require('../models/Record');

module.exports = function(router) {

  /**
   *  API!
   */

  // ---------------------------------------------
  // RECORDS
  // ---------------------------------------------

  // GET all records (admin only)
  router.get('/records', isLoggedIn, function(req, res){
    res.json({message: 'yay logged in'})
  });

  // POST - Create a new user (admin only)
  router.post('/records', isLoggedIn, function(req, res){
    var record = new Record(req.body);
    record.save();
    // Send back the record when saved
    // TODO: Add error handling on save
    res.json(record)
  });

  // GET a specific record
  router.get('/records/:id', function(req, res){
    Record.findById(req.params.id, function(err, doc){
      if (err) {
        return res.json(err)
      }
      if (!doc) {
        return res.json({message: 'Record does not exist.'})
      }
      return res.json(doc);
    });
  });

  // PUT - Update a specific Record JSON
  router.put('/records/:id', function(req, res){
    var id = req.params.username;
    res.json({msg: "Updated :)", id: id})
  });

  // Middleware to handle authenticated requests
  function isLoggedIn(req, res, next){
    if (req.isAuthenticated()){
      return next()
    }
    res.json({message: 'Not authorized!'})
  }

};
<commit_msg>return all records for admin<commit_after>var Record = require('../models/Record');

module.exports = function(router) {

  // Middleware to handle authenticated requests
  function isLoggedIn(req, res, next){
    if (req.isAuthenticated()){
      return next()
    }
    res.json({message: 'Not authorized!'})
  }

  /**
   *  API!
   */

  // ---------------------------------------------
  // RECORDS
  // ---------------------------------------------

  // GET all records (admin only)
  router.get('/records', isLoggedIn, function(req, res){
    Record.find({}, function(err, users){
      res.json(users);
    })
  });

  // POST - Create a new user (admin only)
  router.post('/records', isLoggedIn, function(req, res){
    var record = new Record(req.body);
    record.save();
    // Send back the record when saved
    // TODO: Add error handling on save
    res.json(record)
  });

  // GET a specific record
  router.get('/records/:id', function(req, res){
    Record.findById(req.params.id, function(err, doc){
      if (err) {
        return res.json(err)
      }
      if (!doc) {
        return res.json({message: 'Record does not exist.'})
      }
      return res.json(doc);
    });
  });

  // PUT - Update a specific Record
  router.put('/records/:id', function(req, res){
    var id = req.params.username;
    res.json({msg: "Updated :)", id: id})
  });

};
<|endoftext|>


<commit_before>const config = require("./../config.json");
const MSS = require("./../functions/");

module.exports = function(message) {
	if(message.author.id === config.MSS.sysadmin) {
		let input = message.content.replace (/\n/g, "").split(" ");
		input[0] = input[0].substring(config.MSS.prefix.length);
		eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
	} else {
		MSS.msg.react(false, "X");
	}
}

<commit_msg>forgot message<commit_after>const config = require("./../config.json");
const MSS = require("./../functions/");

module.exports = function(message) {
	if(message.author.id === config.MSS.sysadmin) {
		let input = message.content.replace (/\n/g, "").split(" ");
		input[0] = input[0].substring(config.MSS.prefix.length);
		eval(message.content.substring(config.MSS.prefix.length + input[0].length + 1));
	} else {
		MSS.msg.react(message, false, "X");
	}
}

<|endoftext|>


<commit_before>import database from './database';

/**
 * The PostIt class
 * @author Babatunde Adeyemi <tundewrites@gmail.com>
 * @class
 */
class PostIt {

  /**
   * Initializes the database connection
   * Initializes the database models
   * @constructor
   */
  constructor() {
    this.database = database;
  }

  /**
   * Registers new user's info to database
   * @param {string} firstName - User's first name
   * @param {string} lastName - User's last name
   * @param {string} email - User's email
   * @param {string} phone - User's phone
   * @param {string} password - User's password
   * @returns {Promise} - returns a Promise
   */
  registerUser(firstName, lastName, email, phone, password) {
    return this.database.connection.sync().then(() =>
      this.database.User.create({
        firstName,
        lastName,
        email,
        phone,
        password
      })
    );
  }

  /**
   * Fetches a user's details
   * @param {string} email - Signin email address
   * @param {string} password - Signin password
   * @returns {Promise} - returns a Promise
   */
  findUser(email) {
    return this.database.User.findOne({
      where: {
        email
      }
    });
  }

  /**
   * Fetches a group's details
   * @param {string} groupId - groupId of a particular group
   * @returns {Promise}- returns a Promise
   */
  findGroup(groupId) {
    return this.database.Group.findOne({
      where: {
        groupId
      }
    });
  }
  /**
   * Creates a new group for a user
   * @param {string} name - Name of the group
   * @param {string} userId - userId of the creator
   * @returns {Promise} - returns a Promise
   */
  creatGroup(name, userId) {
    return this.database.connection.sync().then(() =>
      this.database.Group.create({
        name,
        userId
      })
    );
  }

  /**
   * Posts a message to a group
   * @param {string} inGroup - groupId of target group
   * @param {string} author - userId of the User
   * @param {string} body - Message content
   * @param {string} priority - Type of message
   * @return {Promise} - returns a Promise
   */
  postMessage(inGroup, author, body, priority) {
    return this.database.connection.sync().then(() =>
      this.database.Message.create({
        inGroup,
        author,
        body,
        priority
      })
    );
  }
}

export default PostIt;
<commit_msg>Add find group method<commit_after>import database from './database';

/**
 * The PostIt class
 * @author Babatunde Adeyemi <tundewrites@gmail.com>
 * @class
 */
class PostIt {

  /**
   * Initializes the database connection
   * Initializes the database models
   * @constructor
   */
  constructor() {
    this.database = database;
  }

  /**
   * Registers new user's info to database
   * @param {string} firstName - User's first name
   * @param {string} lastName - User's last name
   * @param {string} email - User's email
   * @param {string} phone - User's phone
   * @param {string} password - User's password
   * @returns {Promise} - returns a Promise
   */
  registerUser(firstName, lastName, email, phone, password) {
    return this.database.connection.sync().then(() =>
      this.database.User.create({
        firstName,
        lastName,
        email,
        phone,
        password
      })
    );
  }

  /**
   * Fetches a user's details
   * @param {string} email - Signin email address
   * @returns {Promise} - returns a Promise
   */
  findUser(email) {
    return this.database.User.findOne({
      where: {
        email
      }
    });
  }

  /**
   * Fetches a group's details
   * @param {string} groupId - groupId of a particular group
   * @returns {Promise}- returns a Promise
   */
  findGroup(groupId) {
    return this.database.Group.findOne({
      where: {
        groupId
      }
    });
  }

  /**
   * Creates a new group for a user
   * @param {string} name - Name of the group
   * @param {string} userId - userId of the creator
   * @returns {Promise} - returns a Promise
   */
  creatGroup(name, userId) {
    return this.database.connection.sync().then(() =>
      this.database.Group.create({
        name,
        userId
      })
    );
  }

  /**
   * Posts a message to a group
   * @param {string} inGroup - groupId of target group
   * @param {string} author - userId of the User
   * @param {string} body - Message content
   * @param {string} priority - Type of message
   * @return {Promise} - returns a Promise
   */
  postMessage(inGroup, author, body, priority) {
    return this.database.connection.sync().then(() =>
      this.database.Message.create({
        inGroup,
        author,
        body,
        priority
      })
    );
  }

  /**
   * Adds a member to a group
   * @param {string} userId - userId of the user
   * @param {string} groupId - groupId of the group
   * @returns {Promise} - returns a Promise
   */
  addGroupMember(userId, groupId) {
    return this.database.connection.sync().then(() =>
      this.database.GroupMember.create({
        userId,
        groupId
      })
    );
  }

}

export default PostIt;
<|endoftext|>


<commit_before>/* @flow strict-local */
import { connect } from 'react-redux';

import React, { PureComponent } from 'react';
import { StyleSheet, View, ScrollView } from 'react-native';

import type {
  ChildrenArray,
  Context,
  Dimensions,
  GlobalState,
  LocalizableText,
  Style,
} from '../types';
import KeyboardAvoider from './KeyboardAvoider';
import OfflineNotice from './OfflineNotice';
import ZulipStatusBar from './ZulipStatusBar';
import { getSession } from '../selectors';
import ModalNavBar from '../nav/ModalNavBar';
import ModalSearchNavBar from '../nav/ModalSearchNavBar';
import styles from '../styles';

const componentStyles = StyleSheet.create({
  wrapper: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  childrenWrapper: {
    flex: 1,
  },
  content: {
    flexGrow: 1,
    justifyContent: 'center',
  },
});

type Props = {|
  autoFocus: boolean,
  centerContent: boolean,
  children: ChildrenArray<*>,
  safeAreaInsets: Dimensions,
  keyboardShouldPersistTaps?: 'never' | 'always' | 'handled',
  padding: boolean,
  search: boolean,
  title?: LocalizableText,
  scrollEnabled?: boolean,
  style?: Style,
  searchBarOnChange?: (text: string) => void,
|};

/**
 * A component representing a distinct screen of the app
 * ensuring consistent look-and-feel throughout.
 * It can control the status bar, can render a nav bar or
 * include a search input, center its contents, etc.
 *
 * @prop [autoFocus] - If search bar enabled, should it be focused initially.
 * @prop [centerContent] - Should the contents be centered.
 * @prop children - Components to render inside the screen.
 * @prop safeAreaInsets - Supports safe area edge offsetting. Google 'iOS Safe Area'.
 * @prop [keyboardShouldPersistTaps] - Sets the same prop value to the internal
 *   ScrollView component.
 * @prop [padding] - Should padding be added to the contents of the screen.
 * @prop [search] - If 'true' show a search box in place of the title.
 * @prop [title] - Text shown as the title of the screen.
 * @prop [style] - Additional style for the wrapper container.
 * @prop searchBarOnChange - Event called on search query change.
 */
class Screen extends PureComponent<Props> {
  context: Context;

  static contextTypes = {
    styles: () => null,
  };

  static defaultProps = {
    autoFocus: false,
    centerContent: false,
    keyboardShouldPersistTaps: 'handled',
    padding: false,
    scrollEnabled: true,
    search: false,
  };

  render() {
    const {
      autoFocus,
      centerContent,
      children,
      keyboardShouldPersistTaps,
      padding,
      safeAreaInsets,
      scrollEnabled,
      search,
      searchBarOnChange,
      style,
      title,
    } = this.props;
    const { styles: contextStyles } = this.context;

    return (
      <View style={[contextStyles.screen, { marginBottom: safeAreaInsets.bottom }]}>
        {/* $FlowFixMe-56 Cannot create ZulipStatusBar element because ST is not a React component. */}
        <ZulipStatusBar />
        {search ? (
          <ModalSearchNavBar autoFocus={autoFocus} searchBarOnChange={searchBarOnChange} />
        ) : (
          <ModalNavBar title={title} />
        )}
        <OfflineNotice />
        <KeyboardAvoider
          behavior="padding"
          style={[componentStyles.wrapper, padding && styles.padding]}
          contentContainerStyle={[padding && styles.padding]}
        >
          <ScrollView
            contentContainerStyle={
              /* $FlowFixMe wants ViewStyleProp */
              [styles.flexed, centerContent && componentStyles.content, style]
            }
            style={componentStyles.childrenWrapper}
            keyboardShouldPersistTaps={keyboardShouldPersistTaps}
            scrollEnabled={scrollEnabled}
          >
            {children}
          </ScrollView>
        </KeyboardAvoider>
      </View>
    );
  }
}

export default connect((state: GlobalState) => ({
  safeAreaInsets: getSession(state).safeAreaInsets,
}))(Screen);
<commit_msg>layout: Include bottom "safe area" in painting background color.<commit_after>/* @flow strict-local */
import { connect } from 'react-redux';

import React, { PureComponent } from 'react';
import { StyleSheet, View, ScrollView } from 'react-native';

import type {
  ChildrenArray,
  Context,
  Dimensions,
  GlobalState,
  LocalizableText,
  Style,
} from '../types';
import KeyboardAvoider from './KeyboardAvoider';
import OfflineNotice from './OfflineNotice';
import ZulipStatusBar from './ZulipStatusBar';
import { getSession } from '../selectors';
import ModalNavBar from '../nav/ModalNavBar';
import ModalSearchNavBar from '../nav/ModalSearchNavBar';
import styles from '../styles';

const componentStyles = StyleSheet.create({
  wrapper: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  childrenWrapper: {
    flex: 1,
  },
  content: {
    flexGrow: 1,
    justifyContent: 'center',
  },
});

type Props = {|
  autoFocus: boolean,
  centerContent: boolean,
  children: ChildrenArray<*>,
  safeAreaInsets: Dimensions,
  keyboardShouldPersistTaps?: 'never' | 'always' | 'handled',
  padding: boolean,
  search: boolean,
  title?: LocalizableText,
  scrollEnabled?: boolean,
  style?: Style,
  searchBarOnChange?: (text: string) => void,
|};

/**
 * A component representing a distinct screen of the app
 * ensuring consistent look-and-feel throughout.
 * It can control the status bar, can render a nav bar or
 * include a search input, center its contents, etc.
 *
 * @prop [autoFocus] - If search bar enabled, should it be focused initially.
 * @prop [centerContent] - Should the contents be centered.
 * @prop children - Components to render inside the screen.
 * @prop safeAreaInsets - Supports safe area edge offsetting. Google 'iOS Safe Area'.
 * @prop [keyboardShouldPersistTaps] - Sets the same prop value to the internal
 *   ScrollView component.
 * @prop [padding] - Should padding be added to the contents of the screen.
 * @prop [search] - If 'true' show a search box in place of the title.
 * @prop [title] - Text shown as the title of the screen.
 * @prop [style] - Additional style for the wrapper container.
 * @prop searchBarOnChange - Event called on search query change.
 */
class Screen extends PureComponent<Props> {
  context: Context;

  static contextTypes = {
    styles: () => null,
  };

  static defaultProps = {
    autoFocus: false,
    centerContent: false,
    keyboardShouldPersistTaps: 'handled',
    padding: false,
    scrollEnabled: true,
    search: false,
  };

  render() {
    const {
      autoFocus,
      centerContent,
      children,
      keyboardShouldPersistTaps,
      padding,
      safeAreaInsets,
      scrollEnabled,
      search,
      searchBarOnChange,
      style,
      title,
    } = this.props;
    const { styles: contextStyles } = this.context;

    return (
      <View style={[contextStyles.screen, { paddingBottom: safeAreaInsets.bottom }]}>
        {/* $FlowFixMe-56 Cannot create ZulipStatusBar element because ST is not a React component. */}
        <ZulipStatusBar />
        {search ? (
          <ModalSearchNavBar autoFocus={autoFocus} searchBarOnChange={searchBarOnChange} />
        ) : (
          <ModalNavBar title={title} />
        )}
        <OfflineNotice />
        <KeyboardAvoider
          behavior="padding"
          style={[componentStyles.wrapper, padding && styles.padding]}
          contentContainerStyle={[padding && styles.padding]}
        >
          <ScrollView
            contentContainerStyle={
              /* $FlowFixMe wants ViewStyleProp */
              [styles.flexed, centerContent && componentStyles.content, style]
            }
            style={componentStyles.childrenWrapper}
            keyboardShouldPersistTaps={keyboardShouldPersistTaps}
            scrollEnabled={scrollEnabled}
          >
            {children}
          </ScrollView>
        </KeyboardAvoider>
      </View>
    );
  }
}

export default connect((state: GlobalState) => ({
  safeAreaInsets: getSession(state).safeAreaInsets,
}))(Screen);
<|endoftext|>


<commit_before>import database from './database';

/**
 * The PostIt class
 * @author Babatunde Adeyemi <tundewrites@gmail.com>
 * @class
 */
class PostIt {

  /**
   * Initializes the database connection
   * Initializes the database models
   * @constructor
   */
  constructor() {
    this.database = database;
  }

  /**
   * Registers new user's info to database
   * @param {string} firstName - User's first name
   * @param {string} lastName - User's last name
   * @param {string} email - User's email
   * @param {string} phone - User's phone
   * @param {string} password - User's password
   * @returns {Promise} - returns a Promise
   */
  registerUser(firstName, lastName, email, phone, password) {
    return this.database.connection.sync().then(() =>
      this.database.User.create({
        firstName,
        lastName,
        email,
        phone,
        password
      })
    );
  }

  /**
   * Fetches a user's details
   * @param {string} email - Signin email address
   * @returns {Promise} - returns a Promise
   */
  findUser(email) {
    return this.database.User.findOne({
      where: {
        email
      }
    });
  }

  /**
   * Fetches a group's details
   * @param {string} groupId - groupId of a particular group
   * @returns {Promise}- returns a Promise
   */
  findGroup(groupId) {
    return this.database.Group.findOne({
      where: {
        groupId
      }
    });
  }

  /**
   * Creates a new group for a user
   * @param {string} name - Name of the group
   * @param {string} userId - userId of the creator
   * @returns {Promise} - returns a Promise
   */
  creatGroup(name, userId) {
    return this.database.connection.sync().then(() =>
      this.database.Group.create({
        name,
        userId
      })
    );
  }

  /**
   * Posts a message to a group
   * @param {string} inGroup - groupId of target group
   * @param {string} author - userId of the User
   * @param {string} body - Message content
   * @param {string} priority - Type of message
   * @return {Promise} - returns a Promise
   */
  postMessage(inGroup, author, body, priority) {
    return this.database.connection.sync().then(() =>
      this.database.Message.create({
        inGroup,
        author,
        body,
        priority
      })
    );
  }

  /**
   * Adds a member to a group
   * @param {string} userId - userId of the user
   * @param {string} groupId - groupId of the group
   * @returns {Promise} - returns a Promise
   */
  addGroupMember(userId, groupId) {
    return this.database.connection.sync().then(() =>
      this.database.GroupMember.create({
        userId,
        groupId
      })
    );
  }

}

export default PostIt;
<commit_msg>Add getMessages method to retrieve all messages in a particular group<commit_after>import database from './database';

/**
 * The PostIt class
 * @author Babatunde Adeyemi <tundewrites@gmail.com>
 * @class
 */
class PostIt {

  /**
   * Initializes the database connection
   * Initializes the database models
   * @constructor
   */
  constructor() {
    this.database = database;
  }

  /**
   * Registers new user's info to database
   * @param {string} firstName - User's first name
   * @param {string} lastName - User's last name
   * @param {string} email - User's email
   * @param {string} phone - User's phone
   * @param {string} password - User's password
   * @returns {Promise} - returns a Promise
   */
  registerUser(firstName, lastName, email, phone, password) {
    return this.database.connection.sync().then(() =>
      this.database.User.create({
        firstName,
        lastName,
        email,
        phone,
        password
      })
    );
  }

  /**
   * Fetches a user's details
   * @param {string} email - Signin email address
   * @returns {Promise} - returns a Promise
   */
  findUser(email) {
    return this.database.User.findOne({
      where: {
        email
      }
    });
  }

  /**
   * Fetches a group's details
   * @param {string} groupId - groupId of a particular group
   * @returns {Promise}- returns a Promise
   */
  findGroup(groupId) {
    return this.database.Group.findOne({
      where: {
        groupId
      }
    });
  }

  /**
   * Creates a new group for a user
   * @param {string} name - Name of the group
   * @param {string} userId - userId of the creator
   * @returns {Promise} - returns a Promise
   */
  creatGroup(name, userId) {
    return this.database.connection.sync().then(() =>
      this.database.Group.create({
        name,
        userId
      })
    );
  }

  /**
   * Posts a message to a group
   * @param {string} inGroup - groupId of target group
   * @param {string} author - userId of the User
   * @param {string} body - Message content
   * @param {string} priority - Type of message
   * @return {Promise} - returns a Promise
   */
  postMessage(inGroup, author, body, priority) {
    return this.database.connection.sync().then(() =>
      this.database.Message.create({
        inGroup,
        author,
        body,
        priority
      })
    );
  }

  /**
   * Adds a member to a group
   * @param {string} userId - userId of the user
   * @param {string} groupId - groupId of the group
   * @returns {Promise} - returns a Promise
   */
  addGroupMember(userId, groupId) {
    return this.database.connection.sync().then(() =>
      this.database.GroupMember.create({
        userId,
        groupId
      })
    );
  }

  /**
   * Fetches all messages in a particular group
   * @param {string} groupId - target group
   * @returns {Promise} - returns a Promise
   */
  getMessages(groupId) {
    return this.database.Message.findAll({
      where: {
        inGroup: groupId
      }
    });
  }
}

export default PostIt;
<|endoftext|>


<commit_before>console.log("Awolumate Samuel");
console.log("I am ThirdSamuel");

/*14 - number
-80 - number
8.5 - number
true - boolean
(5 < 7) - boolean
null - unidentified
3.142 - number
"pi" - string
67 + 18 - number
*/

//CONVERTING BINARY TO DECIMAL
function DecimalToBinary(DecimalValue){
		var BinaryValue = '';
		// Loop from 2^64/2 to 1
		for (var i=64; i>=1; i--){
			// Is 2^i/2 within DecimalValue?
			if(DecimalValue >= Math.pow(2,i)/2){
				// If so, add a 1 to BinaryValue and subtract 2^i/2 from DecimalValue
				BinaryValue = BinaryValue+'1';
				DecimalValue = DecimalValue - (Math.pow(2,i)/2);
			}
			else if(BinaryValue.indexOf("1") != -1){
				// If not, add a 0, but only if there is already a 1 in the value
				BinaryValue = BinaryValue+'0';
			}
		}
		return BinaryValue;
	}
	function BinaryToDecimal(BinaryValue){
		var DecimalValue = 0;
		// Flip the character array (aka string) in order to make itterating over it easier
		BinaryValue = BinaryValue.split("").reverse().join("");
		// Loop over BinaryValue (from left to right)
		for (var i=BinaryValue.length-1;i>=0;i--){
			// Is there a 1 in the place?
			if(BinaryValue[i] == '1'){
				// If so, add 2^i/2 to DecimalValue
				DecimalValue = DecimalValue + (Math.pow(2,i+1)/2);
			}
		}
		return DecimalValue;
	};

	//ASSIGNMENT 3
	var countBs = function(proteins) {
	var num = 0;
	for (var i = 0; i < proteins.length; i++){
		if (proteins.charAt(i) === "B"){
			num ++;
		}
	} console.log(num)
}
countBs("My Best Food")

var countChar = function (proteins, checkthis){
var num = 0;
	for (var i = 0; i < proteins.length; i++){
		if (proteins.charAt(i) === checkthis){
			num ++;
		}

	} console.log(num)
}
countChar("My Best Food", "m");<commit_msg>"I just commit an updated file "<commit_after>console.log("Awolumate Samuel");
console.log("I am ThirdSamuel");

/*14 - number
-80 - number
8.5 - number
true - boolean
(5 < 7) - boolean
null - unidentified
3.142 - number
"pi" - string
67 + 18 - number
*/

//CONVERTING BINARY TO DECIMAL
function DecimalToBinary(DecimalValue){

		var BinaryValue = '';
		// Loop from 2^64/2 to 1

		for (var i = 64; i > = 1; i--){
			// Is 2^i/2 within DecimalValue?

			if (DecimalValue >= Math.pow (2,i) / 2){
				// If so, add a 1 to BinaryValue and subtract 2^i/2 from DecimalValue
				BinaryValue = BinaryValue + '1';
				DecimalValue = DecimalValue - (Math.pow (2,i) /2);
			}
			else if (BinaryValue.indexOf("1") != -1){
				// If not, add a 0, but only if there is already a 1 in the value
				BinaryValue = BinaryValue +'0';
			}
		}
		return BinaryValue;
	};

	function BinaryToDecimal(BinaryValue){
		var DecimalValue = 0;
		// Flip the character array (aka string) in order to make itterating over it easier
		BinaryValue = BinaryValue.split("").reverse().join("");
		// Loop over BinaryValue (from left to right)
		for (var i=BinaryValue.length-1;i>=0;i--){
			// Is there a 1 in the place?
			if(BinaryValue[i] == '1'){
				// If so, add 2^i/2 to DecimalValue
				DecimalValue = DecimalValue + (Math.pow(2,i+1)/2);
			}
		}
		return DecimalValue;
	};

	//ASSIGNMENT 3
	/*var countBs = function(proteins) {
	var num = 0;
	for (var i = 0; i < proteins.length; i++){
		if (proteins.charAt(i) === "B"){
			num ++;
		}
	} console.log(num)
}
countBs("My Best Food")

var countChar = function (proteins, checkthis){
var num = 0;
	for (var i = 0; i < proteins.length; i++){
		if (proteins.charAt(i) === checkthis){
			num ++;
		}

	} console.log(num)
}
countChar("My Best Food", "m");
*/
//Exercice 4

var looping = function(nextnum) {
    var a = b = 1; n = 2
    for(var i = 0; i <= nextnum; i++) {
        n = a + b; a = b; b = n;
      console.log(n);
    }

};

   looping(15);

//Exercise 5
function factorial(num)
{
    // If the number is less than 0, reject it.
    if (num < 0) {
        return -1;
    }
    // If the number is 0, its factorial is 1.
    else if (num == 0) {
        return 1;
    }
    // Otherwise, call this recursive procedure again.
    else {
        return (num * factorial(num - 1));
    }
};

//This can also be written as this

function factorial(n)
{
	var loop, answer;
	answer = 1;

	for(loop=1;loop<=n;loop++)
	{

		answer = answer * loop;

	}

	return answer;
}; //Both will run

// I HOPE THIS CODES ARE BETTER SCRIPTED COMPARE TO THAT OF YESTERDAY?<|endoftext|>


<commit_before>/*#ifndef(UMD)*/
"use strict";
/*exported _gpfArraySlice*/
/*exported _gpfJsCommentsRegExp*/
/*#endif*/

/*eslint-disable no-proto*/ // Used for compatibility reasons
/*jshint -W103*/

var _gpfArrayPrototypeSlice = Array.prototype.slice;

/**
 * Slice an array-like object
 *
 * @param {Object} array array-like parameter (arguments, Array)
 * @param {Number} from
 * @param {Number} [to=undefined] to
 * @return {Array}
 */
function _gpfArraySlice (array, from, to) {
    return _gpfArrayPrototypeSlice.apply(array, [from || 0, to || array.length + 1]);
}

var _gpfCompatibility = {

    Array: {
        on: Array.prototype,

        // Introduced with JavaScript 1.6
        every: function (callback) {
            var thisArg = arguments[1],
                len = this.length,
                idx;
            for (idx = 0; idx < len; ++idx) {
                if (!callback.apply(thisArg, [this[idx], idx, this])) {
                    return false;
                }
            }
            return true;
        },

        // Introduced with JavaScript 1.6
        filter: function (callback) {
            var thisArg = arguments[1],
                result = [],
                len = this.length,
                idx,
                item;
            for (idx = 0; idx < len; ++idx) {
                item = this[idx];
                if (callback.apply(thisArg, [this[idx], idx, this])) {
                    result.push(item);
                }
            }
            return result;
        },

        // Introduced with JavaScript 1.6
        forEach: function (callback) {
            var thisArg = arguments[1],
                len = this.length,
                idx;
            for (idx = 0; idx < len; ++idx) {
                callback.apply(thisArg, [this[idx], idx, this]);
            }
        },

        // Introduced with JavaScript 1.5
        indexOf: function (searchElement) {
            var fromIndex = arguments[1],
                index = fromIndex || 0,
                thisLength = this.length;
            while (index < thisLength) {
                if (this[index] === searchElement) {
                    return index;
                }
                ++index;
            }
            return -1;
        },

        // Introduced with JavaScript 1.6
        map: function (callback) {
            var thisArg = arguments[1],
                thisLength = this.length,
                result = new Array(thisLength),
                index;
            for (index = 0; index < thisLength; ++index) {
                result[index] = callback.apply(thisArg, [this[index], index, this]);
            }
            return result;
        },

        // Introduced with JavaScript 1.8
        reduce: function (callback) {
            var initialValue = arguments[1],
                thisLength = this.length,
                index = 0,
                value;
            if (undefined === initialValue) {
                value = this[index++];
            } else {
                value = initialValue;
            }
            for (; index < thisLength; ++index) {
                value = callback(value, this[index], index, this);
            }
            return value;
        }

    },

    Function: {
        on: Function.prototype,

        // Introduced with JavaScript 1.8.5
        bind: function (thisArg) {
            var me = this,
                prependArgs = _gpfArraySlice(arguments, 1);
            return function () {
                var args = _gpfArraySlice(arguments, 0);
                me.apply(thisArg, prependArgs.concat(args));
            };
        }

    },

    Object: {
        on: Object,

        create: (function () {
            function Temp () {}
            return function (O) {
                Temp.prototype = O;
                var obj = new Temp();
                Temp.prototype = null;
                if (!obj.__proto__) {
                    obj.__proto__ = O;
                }
                return obj;
            };
        }()),

        getPrototypeOf: function (object) {
            // May break if the constructor has been tampered with
            return object.__proto__ || object.constructor.prototype;
        }

    },

    String: {
        on: String.prototype,

        // Introduced with JavaScript 1.8.1
        trim: (function () {
            var rtrim = new RegExp("^[\\s\uFEFF\xA0]+|[\\s\uFEFF\xA0]+$", "g");
            return function () {
                return this.replace(rtrim, "");
            };
        }())

    }

};

(function () {
    var type,
        compatibleMethods;

    function install (dictionary, methods) {
        for (var name in methods) {
            /* istanbul ignore else */
            if (methods.hasOwnProperty(name)) {
                if (name === "on") {
                    continue;
                }
                /* istanbul ignore if */ // NodeJS environment already contains all methods
                if (undefined === dictionary[name]) {
                    dictionary[name] = methods[name];
                }
            }
        }
    }

    for (type in _gpfCompatibility) {
        /* istanbul ignore else */
        if (_gpfCompatibility.hasOwnProperty(type)) {
            compatibleMethods = _gpfCompatibility[type];
            install(compatibleMethods.on, compatibleMethods);
        }
    }

}());

// Get the name of a function if bound to the call
var _gpfJsCommentsRegExp =  new RegExp("//.*$|/\\*.*\\*/", "g");
function _gpfGetFunctionName () {
    // Use simple parsing
    /*jshint validthis:true*/
    var functionSource = Function.prototype.toString.apply(this), //eslint-disable-line no-invalid-this
        functionKeywordPos = functionSource.indexOf("function"),
        parameterListStartPos = functionSource.indexOf("(", functionKeywordPos);
    return functionSource
            .substr(functionKeywordPos + 9, parameterListStartPos - functionKeywordPos - 9)
            .replace(_gpfJsCommentsRegExp, "") // remove comments
            .trim();
}

// Handling function name properly
/* istanbul ignore if */ // NodeJS exposes Function.prototype.name
if ((function () {
    /* istanbul ignore next */ // Will never be evaluated
    function functionName () {}
    return functionName.name !== "functionName";
})()) {

    Function.prototype.compatibleName = _gpfGetFunctionName;

} else {

    /**
     * Return function name
     *
     * @return {String}
     */
    Function.prototype.compatibleName = function () {
        return this.name;
    };

}

/*#ifndef(UMD)*/

gpf.internals._gpfArraySlice = _gpfArraySlice;
gpf.internals._gpfCompatibility = _gpfCompatibility;
gpf.internals._gpfGetFunctionName = _gpfGetFunctionName;

/*#endif*/
<commit_msg>Fixed comments regexp<commit_after>/*#ifndef(UMD)*/
"use strict";
/*exported _gpfArraySlice*/
/*exported _gpfJsCommentsRegExp*/
/*#endif*/

/*eslint-disable no-proto*/ // Used for compatibility reasons
/*jshint -W103*/

var _gpfArrayPrototypeSlice = Array.prototype.slice;

/**
 * Slice an array-like object
 *
 * @param {Object} array array-like parameter (arguments, Array)
 * @param {Number} from
 * @param {Number} [to=undefined] to
 * @return {Array}
 */
function _gpfArraySlice (array, from, to) {
    return _gpfArrayPrototypeSlice.apply(array, [from || 0, to || array.length + 1]);
}

var _gpfCompatibility = {

    Array: {
        on: Array.prototype,

        // Introduced with JavaScript 1.6
        every: function (callback) {
            var thisArg = arguments[1],
                len = this.length,
                idx;
            for (idx = 0; idx < len; ++idx) {
                if (!callback.apply(thisArg, [this[idx], idx, this])) {
                    return false;
                }
            }
            return true;
        },

        // Introduced with JavaScript 1.6
        filter: function (callback) {
            var thisArg = arguments[1],
                result = [],
                len = this.length,
                idx,
                item;
            for (idx = 0; idx < len; ++idx) {
                item = this[idx];
                if (callback.apply(thisArg, [this[idx], idx, this])) {
                    result.push(item);
                }
            }
            return result;
        },

        // Introduced with JavaScript 1.6
        forEach: function (callback) {
            var thisArg = arguments[1],
                len = this.length,
                idx;
            for (idx = 0; idx < len; ++idx) {
                callback.apply(thisArg, [this[idx], idx, this]);
            }
        },

        // Introduced with JavaScript 1.5
        indexOf: function (searchElement) {
            var fromIndex = arguments[1],
                index = fromIndex || 0,
                thisLength = this.length;
            while (index < thisLength) {
                if (this[index] === searchElement) {
                    return index;
                }
                ++index;
            }
            return -1;
        },

        // Introduced with JavaScript 1.6
        map: function (callback) {
            var thisArg = arguments[1],
                thisLength = this.length,
                result = new Array(thisLength),
                index;
            for (index = 0; index < thisLength; ++index) {
                result[index] = callback.apply(thisArg, [this[index], index, this]);
            }
            return result;
        },

        // Introduced with JavaScript 1.8
        reduce: function (callback) {
            var initialValue = arguments[1],
                thisLength = this.length,
                index = 0,
                value;
            if (undefined === initialValue) {
                value = this[index++];
            } else {
                value = initialValue;
            }
            for (; index < thisLength; ++index) {
                value = callback(value, this[index], index, this);
            }
            return value;
        }

    },

    Function: {
        on: Function.prototype,

        // Introduced with JavaScript 1.8.5
        bind: function (thisArg) {
            var me = this,
                prependArgs = _gpfArraySlice(arguments, 1);
            return function () {
                var args = _gpfArraySlice(arguments, 0);
                me.apply(thisArg, prependArgs.concat(args));
            };
        }

    },

    Object: {
        on: Object,

        create: (function () {
            function Temp () {}
            return function (O) {
                Temp.prototype = O;
                var obj = new Temp();
                Temp.prototype = null;
                if (!obj.__proto__) {
                    obj.__proto__ = O;
                }
                return obj;
            };
        }()),

        getPrototypeOf: function (object) {
            // May break if the constructor has been tampered with
            return object.__proto__ || object.constructor.prototype;
        }

    },

    String: {
        on: String.prototype,

        // Introduced with JavaScript 1.8.1
        trim: (function () {
            var rtrim = new RegExp("^[\\s\uFEFF\xA0]+|[\\s\uFEFF\xA0]+$", "g");
            return function () {
                return this.replace(rtrim, "");
            };
        }())

    }

};

(function () {
    var type,
        compatibleMethods;

    function install (dictionary, methods) {
        for (var name in methods) {
            /* istanbul ignore else */
            if (methods.hasOwnProperty(name)) {
                if (name === "on") {
                    continue;
                }
                /* istanbul ignore if */ // NodeJS environment already contains all methods
                if (undefined === dictionary[name]) {
                    dictionary[name] = methods[name];
                }
            }
        }
    }

    for (type in _gpfCompatibility) {
        /* istanbul ignore else */
        if (_gpfCompatibility.hasOwnProperty(type)) {
            compatibleMethods = _gpfCompatibility[type];
            install(compatibleMethods.on, compatibleMethods);
        }
    }

}());

// Get the name of a function if bound to the call
var _gpfJsCommentsRegExp =  new RegExp("//.*$|/\\*(?:[^\\*]*|\\*[^/]*)\\*/", "gm");
function _gpfGetFunctionName () {
    // Use simple parsing
    /*jshint validthis:true*/
    var functionSource = Function.prototype.toString.apply(this), //eslint-disable-line no-invalid-this
        functionKeywordPos = functionSource.indexOf("function"),
        parameterListStartPos = functionSource.indexOf("(", functionKeywordPos);
    return functionSource
            .substr(functionKeywordPos + 9, parameterListStartPos - functionKeywordPos - 9)
            .replace(_gpfJsCommentsRegExp, "") // remove comments
            .trim();
}

// Handling function name properly
/* istanbul ignore if */ // NodeJS exposes Function.prototype.name
if ((function () {
    /* istanbul ignore next */ // Will never be evaluated
    function functionName () {}
    return functionName.name !== "functionName";
})()) {

    Function.prototype.compatibleName = _gpfGetFunctionName;

} else {

    /**
     * Return function name
     *
     * @return {String}
     */
    Function.prototype.compatibleName = function () {
        return this.name;
    };

}

/*#ifndef(UMD)*/

gpf.internals._gpfArraySlice = _gpfArraySlice;
gpf.internals._gpfCompatibility = _gpfCompatibility;
gpf.internals._gpfGetFunctionName = _gpfGetFunctionName;

/*#endif*/
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.db = {
	get_list: function(doctype, args) {
		if (!args) {
			args = {};
		}
		args.doctype = doctype;
		if (!args.fields) {
			args.fields = ['name'];
		}
		if (!args.limit) {
			args.limit = 20;
		}
		return new Promise ((resolve) => {
			frappe.call({
				method: 'frappe.desk.reportview.get_list',
				args: args,
				type: 'GET',
				callback: function(r) {
					resolve(r.message);
				}
			});
		});
	},
	exists: function(doctype, name) {
		return new Promise ((resolve) => {
			frappe.db.get_value(doctype, {name: name}, 'name').then((r) => {
				(r.message && r.message.name) ? resolve(true) : resolve(false);
			});
		});
	},
	get_value: function(doctype, filters, fieldname, callback, parent_doc) {
		return frappe.call({
			method: "frappe.client.get_value",
			type: 'GET',
			args: {
				doctype: doctype,
				fieldname: fieldname,
				filters: filters,
				parent: parent_doc
			},
			callback: function(r) {
				callback && callback(r.message);
			}
		});
	},
	get_single_value: (doctype, field) => {
		return new Promise(resolve => {
			frappe.call({
				method: 'frappe.client.get_single_value',
				args: { doctype, field },
				type: 'GET',
			}).then(r => resolve(r ? r.message : null));
		});
	},
	set_value: function(doctype, docname, fieldname, value, callback) {
		return frappe.call({
			method: "frappe.client.set_value",
			args: {
				doctype: doctype,
				name: docname,
				fieldname: fieldname,
				value: value
			},
			callback: function(r) {
				callback && callback(r.message);
			}
		});
	},
	get_doc: function(doctype, name, filters = null) {
		return new Promise((resolve, reject) => {
			frappe.call({
				method: "frappe.client.get",
				type: 'GET',
				args: { doctype, name, filters },
				callback: r => {
					frappe.model.sync(r.message);
					resolve(r.message);
				}
			}).fail(reject);
		});
	},
	insert: function(doc) {
		return frappe.xcall('frappe.client.insert', { doc });
	},
	delete_doc: function(doctype, name) {
		return new Promise(resolve => {
			frappe.call('frappe.client.delete', { doctype, name }, r => resolve(r.message));
		});
	},
	count: function(doctype, args={}) {
		let filters = args.filters || {};

		// has a filter with childtable?
		const distinct = Array.isArray(filters) && filters.some(filter => {
			return filter[0] !== doctype;
		});

		const fields = [];

		return frappe.call({
			type: 'GET',
			method: 'frappe.desk.reportview.get_count',
			args: {
				doctype,
				filters,
				fields,
				distinct,
			}
		}).then(r => {
			return r.message.values;
		});
	},
	get_link_options(doctype, txt = '', filters={}) {
		return new Promise(resolve => {
			frappe.call({
				type: 'GET',
				method: 'frappe.desk.search.search_link',
				args: {
					doctype,
					txt,
					filters
				},
				callback(r) {
					resolve(r.results);
				}
			});
		});
	}
};
<commit_msg>fix: Return correct value from frappe.db.count (#12748)<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.db = {
	get_list: function(doctype, args) {
		if (!args) {
			args = {};
		}
		args.doctype = doctype;
		if (!args.fields) {
			args.fields = ['name'];
		}
		if (!args.limit) {
			args.limit = 20;
		}
		return new Promise ((resolve) => {
			frappe.call({
				method: 'frappe.desk.reportview.get_list',
				args: args,
				type: 'GET',
				callback: function(r) {
					resolve(r.message);
				}
			});
		});
	},
	exists: function(doctype, name) {
		return new Promise ((resolve) => {
			frappe.db.get_value(doctype, {name: name}, 'name').then((r) => {
				(r.message && r.message.name) ? resolve(true) : resolve(false);
			});
		});
	},
	get_value: function(doctype, filters, fieldname, callback, parent_doc) {
		return frappe.call({
			method: "frappe.client.get_value",
			type: 'GET',
			args: {
				doctype: doctype,
				fieldname: fieldname,
				filters: filters,
				parent: parent_doc
			},
			callback: function(r) {
				callback && callback(r.message);
			}
		});
	},
	get_single_value: (doctype, field) => {
		return new Promise(resolve => {
			frappe.call({
				method: 'frappe.client.get_single_value',
				args: { doctype, field },
				type: 'GET',
			}).then(r => resolve(r ? r.message : null));
		});
	},
	set_value: function(doctype, docname, fieldname, value, callback) {
		return frappe.call({
			method: "frappe.client.set_value",
			args: {
				doctype: doctype,
				name: docname,
				fieldname: fieldname,
				value: value
			},
			callback: function(r) {
				callback && callback(r.message);
			}
		});
	},
	get_doc: function(doctype, name, filters = null) {
		return new Promise((resolve, reject) => {
			frappe.call({
				method: "frappe.client.get",
				type: 'GET',
				args: { doctype, name, filters },
				callback: r => {
					frappe.model.sync(r.message);
					resolve(r.message);
				}
			}).fail(reject);
		});
	},
	insert: function(doc) {
		return frappe.xcall('frappe.client.insert', { doc });
	},
	delete_doc: function(doctype, name) {
		return new Promise(resolve => {
			frappe.call('frappe.client.delete', { doctype, name }, r => resolve(r.message));
		});
	},
	count: function(doctype, args={}) {
		let filters = args.filters || {};

		// has a filter with childtable?
		const distinct = Array.isArray(filters) && filters.some(filter => {
			return filter[0] !== doctype;
		});

		const fields = [];

		return frappe.xcall('frappe.desk.reportview.get_count', {
			doctype,
			filters,
			fields,
			distinct,
		});
	},
	get_link_options(doctype, txt = '', filters={}) {
		return new Promise(resolve => {
			frappe.call({
				type: 'GET',
				method: 'frappe.desk.search.search_link',
				args: {
					doctype,
					txt,
					filters
				},
				callback(r) {
					resolve(r.results);
				}
			});
		});
	}
};
<|endoftext|>


<commit_before>'use strict';

require('../globals');

module.exports = data;

var vlfield = require('../field'),
  util = require('../util'),
  time = require('./time');

/**
 * Create Vega's data array from a given encoding.
 *
 * @param  {Encoding} encoding
 * @return {Array} Array of Vega data.
 *                 This always includes a "raw" data table.
 *                 If the encoding contains aggregate value, this will also create
 *                 aggregate table as well.
 */
function data(encoding) {
  var def = [data.raw(encoding)];

  var aggregate = data.aggregate(encoding);
  if (aggregate) def.push(data.aggregate(encoding));

  // TODO add "having" filter here

  // append non-positive filter at the end for the data table
  data.filterNonPositive(def[def.length - 1], encoding);

  return def;
}

data.raw = function(encoding) {
  var raw = {name: RAW};

  // Data source (url or inline)
  if (encoding.hasValues()) {
    raw.values = encoding.data().values;
  } else {
    raw.url = encoding.data().url;
    raw.format = {type: encoding.data().formatType};
  }

  // Set data's format.parse if needed
  var parse = data.raw.formatParse(encoding);
  if (parse) {
    raw.format = raw.format || {};
    raw.format.parse = parse;
  }

  raw.transform = data.raw.transform(encoding);
  return raw;
};

data.raw.formatParse = function(encoding) {
  var parse;

  encoding.forEach(function(field) {
    if (field.type == T) {
      parse = parse || {};
      parse[field.name] = 'date';
    } else if (field.type == Q) {
      if (vlfield.isCount(field)) return;
      parse = parse || {};
      parse[field.name] = 'number';
    }
  });

  return parse;
};

/**
 * Generate Vega transforms for the raw data table.  This can include
 * transforms for time unit, binning and filtering.
 */
data.raw.transform = function(encoding) {
  // time and bin should come before filter so we can filter by time and bin
  return data.raw.transform.time(encoding).concat(
    data.raw.transform.bin(encoding),
    data.raw.transform.filter(encoding)
  );
};

var BINARY = {
  '>':  true,
  '>=': true,
  '=':  true,
  '!=': true,
  '<':  true,
  '<=': true
};

data.raw.transform.time = function(encoding) {
  return encoding.reduce(function(transform, field, encType) {
    if (field.type === T && field.timeUnit) {
      transform.push({
        type: 'formula',
        field: encoding.fieldRef(encType),
        expr: time.formula(field.timeUnit,
                           encoding.fieldRef(encType, {nofn: true, d: true})
                          )
      });
    }
    return transform;
  }, []);
};

data.raw.transform.bin = function(encoding) {
  return encoding.reduce(function(transform, field, encType) {
    if (encoding.bin(encType)) {
      transform.push({
        type: 'bin',
        field: encoding.fieldRef(encType, {nofn: true}),
        output: encoding.fieldRef(encType),
        maxbins: encoding.bin(encType).maxbins
      });
    }
    return transform;
  }, []);
};

data.raw.transform.filter = function(encoding) {
  var filters = encoding.filter().reduce(function(f, filter) {
    var condition = '';
    var operator = filter.operator;
    var operands = filter.operands;

    var d = 'd.' + (encoding._vega2 ? '' : 'data.');

    if (BINARY[operator]) {
      // expects a field and a value
      if (operator === '=') {
        operator = '==';
      }

      var op1 = operands[0];
      var op2 = operands[1];
      condition = d + op1 + ' ' + operator + ' ' + op2;
    } else if (operator === 'notNull') {
      // expects a number of fields
      for (var j=0; j<operands.length; j++) {
        condition += d + operands[j] + '!==null';
        if (j < operands.length - 1) {
          condition += ' && ';
        }
      }
    } else {
      util.warn('Unsupported operator: ', operator);
      return f;
    }
    f.push('(' + condition + ')');
    return f;
  }, []);
  if (filters.length === 0) return [];

  return [{
      type: 'filter',
      test: filters.join(' && ')
  }];
};

data.aggregate = function(encoding) {
  var dims = {}, meas = {};

  encoding.forEach(function(field, encType) {
    if (field.aggregate) {
      if (field.aggregate === 'count') {
        meas.count = {op: 'count', field: '*'};
      }else {
        meas[field.aggregate + '|' + field.name] = {
          op: field.aggregate,
          field: encoding.fieldRef(encType, {nofn: true})
        };
      }
    } else {
      dims[field.name] = encoding.fieldRef(encType);
    }
  });

  dims = util.vals(dims);
  meas = util.vals(meas);

  if (meas.length > 0) {
    return {
      name: AGGREGATE,
      source: RAW,
      transform: [{
        type: 'aggregate',
        groupby: dims,
        fields: meas
      }]
    };
  }

  return null;
};

data.filterNonPositive = function(dataTable, encoding) {
  encoding.forEach(function(field, encType) {
    if (encoding.scale(encType).type === 'log') {
      dataTable.transform.push({
        type: 'filter',
        test: encoding.fieldRef(encType, {d: 1}) + ' > 0'
      });
    }
  });
};
<commit_msg>replace d.data with datum in filter<commit_after>'use strict';

require('../globals');

module.exports = data;

var vlfield = require('../field'),
  util = require('../util'),
  time = require('./time');

/**
 * Create Vega's data array from a given encoding.
 *
 * @param  {Encoding} encoding
 * @return {Array} Array of Vega data.
 *                 This always includes a "raw" data table.
 *                 If the encoding contains aggregate value, this will also create
 *                 aggregate table as well.
 */
function data(encoding) {
  var def = [data.raw(encoding)];

  var aggregate = data.aggregate(encoding);
  if (aggregate) def.push(data.aggregate(encoding));

  // TODO add "having" filter here

  // append non-positive filter at the end for the data table
  data.filterNonPositive(def[def.length - 1], encoding);

  return def;
}

data.raw = function(encoding) {
  var raw = {name: RAW};

  // Data source (url or inline)
  if (encoding.hasValues()) {
    raw.values = encoding.data().values;
  } else {
    raw.url = encoding.data().url;
    raw.format = {type: encoding.data().formatType};
  }

  // Set data's format.parse if needed
  var parse = data.raw.formatParse(encoding);
  if (parse) {
    raw.format = raw.format || {};
    raw.format.parse = parse;
  }

  raw.transform = data.raw.transform(encoding);
  return raw;
};

data.raw.formatParse = function(encoding) {
  var parse;

  encoding.forEach(function(field) {
    if (field.type == T) {
      parse = parse || {};
      parse[field.name] = 'date';
    } else if (field.type == Q) {
      if (vlfield.isCount(field)) return;
      parse = parse || {};
      parse[field.name] = 'number';
    }
  });

  return parse;
};

/**
 * Generate Vega transforms for the raw data table.  This can include
 * transforms for time unit, binning and filtering.
 */
data.raw.transform = function(encoding) {
  // time and bin should come before filter so we can filter by time and bin
  return data.raw.transform.time(encoding).concat(
    data.raw.transform.bin(encoding),
    data.raw.transform.filter(encoding)
  );
};

var BINARY = {
  '>':  true,
  '>=': true,
  '=':  true,
  '!=': true,
  '<':  true,
  '<=': true
};

data.raw.transform.time = function(encoding) {
  return encoding.reduce(function(transform, field, encType) {
    if (field.type === T && field.timeUnit) {
      transform.push({
        type: 'formula',
        field: encoding.fieldRef(encType),
        expr: time.formula(field.timeUnit,
                           encoding.fieldRef(encType, {nofn: true, d: true})
                          )
      });
    }
    return transform;
  }, []);
};

data.raw.transform.bin = function(encoding) {
  return encoding.reduce(function(transform, field, encType) {
    if (encoding.bin(encType)) {
      transform.push({
        type: 'bin',
        field: encoding.fieldRef(encType, {nofn: true}),
        output: encoding.fieldRef(encType),
        maxbins: encoding.bin(encType).maxbins
      });
    }
    return transform;
  }, []);
};

data.raw.transform.filter = function(encoding) {
  var filters = encoding.filter().reduce(function(f, filter) {
    var condition = '';
    var operator = filter.operator;
    var operands = filter.operands;

    var d = encoding._vega2 ? 'datum.' : 'd.data.';

    if (BINARY[operator]) {
      // expects a field and a value
      if (operator === '=') {
        operator = '==';
      }

      var op1 = operands[0];
      var op2 = operands[1];
      condition = d + op1 + ' ' + operator + ' ' + op2;
    } else if (operator === 'notNull') {
      // expects a number of fields
      for (var j=0; j<operands.length; j++) {
        condition += d + operands[j] + '!==null';
        if (j < operands.length - 1) {
          condition += ' && ';
        }
      }
    } else {
      util.warn('Unsupported operator: ', operator);
      return f;
    }
    f.push('(' + condition + ')');
    return f;
  }, []);
  if (filters.length === 0) return [];

  return [{
      type: 'filter',
      test: filters.join(' && ')
  }];
};

data.aggregate = function(encoding) {
  var dims = {}, meas = {};

  encoding.forEach(function(field, encType) {
    if (field.aggregate) {
      if (field.aggregate === 'count') {
        meas.count = {op: 'count', field: '*'};
      }else {
        meas[field.aggregate + '|' + field.name] = {
          op: field.aggregate,
          field: encoding.fieldRef(encType, {nofn: true})
        };
      }
    } else {
      dims[field.name] = encoding.fieldRef(encType);
    }
  });

  dims = util.vals(dims);
  meas = util.vals(meas);

  if (meas.length > 0) {
    return {
      name: AGGREGATE,
      source: RAW,
      transform: [{
        type: 'aggregate',
        groupby: dims,
        fields: meas
      }]
    };
  }

  return null;
};

data.filterNonPositive = function(dataTable, encoding) {
  encoding.forEach(function(field, encType) {
    if (encoding.scale(encType).type === 'log') {
      dataTable.transform.push({
        type: 'filter',
        test: encoding.fieldRef(encType, {d: 1}) + ' > 0'
      });
    }
  });
};
<|endoftext|>


<commit_before>/**
 * Express configuration
 */

'use strict';

var express         = require('express');
var favicon         = require('static-favicon');
var morgan          = require('morgan');
var compression     = require('compression');
var bodyParser      = require('body-parser');
var methodOverride  = require('method-override');
var cookieParser    = require('cookie-parser');
var errorHandler    = require('errorhandler');
var path            = require('path');
var config          = require('./environment');
var uuid            = require('node-uuid');

module.exports = function(app) {
  var env = app.get('env');
  app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
   });

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser('superEmprendimiento2014'));

  app.use(function(req, res, next){
    console.log(req.cookies.JSESSIONID);
    if (!req.cookies.JSESSIONID || req.cookies.JSESSIONID == undefined) {
      var theUuid = uuid.v4();
      console.log("there is not, asigning cookie " + theUuid);
      // Guardo en las sesions con el nombre uuid con el value de un numero aleatorio y expira en una semana
      res.cookie('JSESSIONID', theUuid, {maxAge: 604800000});
    }
    //console.log("there is a cookie, " + req.cookies.uuid);
    next();
  });

  if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    app.set('appPath', 'client');
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }
};<commit_msg>5.01 de la mañana, estoy quemadisimo<commit_after>/**
 * Express configuration
 */

'use strict';

var express         = require('express');
var favicon         = require('static-favicon');
var morgan          = require('morgan');
var compression     = require('compression');
var bodyParser      = require('body-parser');
var methodOverride  = require('method-override');
var cookieParser    = require('cookie-parser');
var errorHandler    = require('errorhandler');
var path            = require('path');
var config          = require('./environment');
var uuid            = require('node-uuid');

module.exports = function(app) {
  var env = app.get('env');
  app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
   });

  app.set('views', config.root + '/server/views');
  app.engine('html', require('ejs').renderFile);
  app.set('view engine', 'html');
  app.use(compression());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(methodOverride());
  app.use(cookieParser('superEmprendimiento2014'));

  app.use(function(req, res, next){
    console.log(req.cookies.JSESSIONID);
    if (!req.cookies.JSESSIONID || req.cookies.JSESSIONID == undefined) {
      console.log("dont have cookie");
      var theUuid = uuid.v4();
      console.log("there is not, asigning cookie " + theUuid);
      // Guardo en las sesions con el nombre uuid con el value de un numero aleatorio y expira en una semana
      console.log("created: " + theUuid);
      res.cookie('JSESSIONID', theUuid, {maxAge: 604800000});
    }
    //console.log("there is a cookie, " + req.cookies.uuid);
    next();
  });

  if ('production' === env) {
    app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
    app.use(express.static(path.join(config.root, 'public')));
    app.set('appPath', config.root + '/public');
    app.use(morgan('dev'));
  }

  if ('development' === env || 'test' === env) {
    app.use(express.static(path.join(config.root, '.tmp')));
    app.use(express.static(path.join(config.root, 'client')));
    app.set('appPath', 'client');
    app.use(morgan('dev'));
    app.use(errorHandler()); // Error handler - has to be last
  }
};<|endoftext|>