<commit_before>let Tadpole = function(location, constraints, canvasLayout) {
  this.location = location;
  this.top = constraints[0];
  this.right = constraints[1];
  this.bottom = constraints[2];
  this.left = constraints[3];
  this.neighborTop = 1; // need to find location of its neighbors
  this.neighborRight = 1;
  this.neighborBottom = 1;
  this.neighborLeft = 1;
  this.constraints = [this.top, this.right, this.bottom, this.left];
  this.finalDetails = this.finalDetails();
  // this.tileOptions = tileOptions;
};

Tadpole.prototype.finalDetails = function() {
  var constraints = this.constraints;
  var shapeAndOrientation = findShapeAndOrientation(constraints); // [shape, orientation]
  updateNeighbors(this);
  return [this.location, shapeAndOrientation[0], shapeAndOrientation[1]];
};

var updateNeighbors = function(this) {
  let myShape = this.finalDetails;
  let topNeighborImpact = lookupImpact(myShape[1], myShape[2], "bottom");
  let rightNeighborImpact = lookupImpact(myShape[1], myShape[2], "left");
  let bottomNeighborImpact = lookupImpact(myShape[1], myShape[2], "top");
  let leftNeighborImpact = lookupImpact(myShape[1], myShape[2], "right");

  this.neighborTop.bottom = topNeighborImpact;
  this.neighborRight.left = rightNeighborImpact;
  this.neighborBottom.top = bottomNeighborImpact;
  this.neighborLeft.right = leftNeighborImpact;
};

let lookupImpact = function(shape, orientation, side) {
  // this will be an index, must return Y (if this shape has a line connecting to that side), N (no line connecting to that side)
}

var findShapeAndOrientation = function(constraints) {
  let topConstraintMatches = tileOptions["top"][constraints[0]];
  let rightConstraintMatches = tileOptions["right"][constraints[1];
  let bottomConstraintMatches = tileOptions["bottom"][constraints[2];
  let leftConstraintMatches = tileOptions["left"][constraints[3];

  let matchAllConstraints = 1; // common elements across these four arrays

  return matchAllConstraints.sample();
};

let tileOptions = {
  "top": {"n": [], "u": tileOptions["all"], "y": [["spoke", "top"],["arc", "right"],["arc", "bottom"],["line", "vertical"],["doubleArc", "top"],["doubleArc", "right"],["doubleArc", "left"],["quadArc", "all"]]},
  "right": [["spoke", "right"],["arc", "bottom"],["arc", "left"],["line", "horizontal"],["doubleArc", "top"],["doubleArc", "right"],["doubleArc", "bottom"],["quadArc", "all"]],
  "bottom": [["spoke", "bottom"],["arc", "top"],["arc", "left"],["line", "vertical"],["doubleArc", "right"],["doubleArc", "bottom"],["doubleArc", "left"],["quadArc", "all"]],
  "left": [["spoke", "left"],["arc", "top"],["arc", "right"],["line", "horizontal"],["doubleArc", "top"],["doubleArc", "bottom"],["doubleArc", "left"],["quadArc", "all"]],
  "all": [["spoke", "top"],["spoke", "right"],["spoke", "bottom"],["spoke", "left"],["arc", "top"],["arc", "right"],["arc", "bottom"],["arc", "left"],["line", "horizontal"],["line", "vertical"],["doubleArc", "top"],["doubleArc", "right"],["doubleArc", "bottom"],["doubleArc", "left"],["quadArc", "all"]]
};

module.exports = Tadpole;<commit_msg>adding sweet shapes and some tadpole refactoring<commit_after>let Tadpole = function(location, constraints, canvasLayout) {
  this.location = location;
  this.top = constraints[0];
  this.right = constraints[1];
  this.bottom = constraints[2];
  this.left = constraints[3];
  this.shape = "tbd"
  this.orientation = "tbd"
  this.neighborTop = 1;
  this.neighborRight = 1;
  this.neighborBottom = 1;
  this.neighborLeft = 1;
  this.constraints = [this.top, this.right, this.bottom, this.left];
  // this.myDetails = this.finalDetails();
  // this.tileOptions = tileOptions;
};

Tadpole.prototype.finalDetails = function() {
  var constraints = this.constraints;
  setShapeAndOrientation(constraints); // [shape, orientation]
  updateNeighbors(this);
  return [this.location, this.shape, this.orientation];
};

var updateNeighbors = function(this) {
  let myShape = this.finalDetails;
  let topNeighborImpact = lookupImpact(myShape[1], myShape[2], "bottom");
  let rightNeighborImpact = lookupImpact(myShape[1], myShape[2], "left");
  let bottomNeighborImpact = lookupImpact(myShape[1], myShape[2], "top");
  let leftNeighborImpact = lookupImpact(myShape[1], myShape[2], "right");

  this.neighborTop.bottom = topNeighborImpact;
  this.neighborRight.left = rightNeighborImpact;
  this.neighborBottom.top = bottomNeighborImpact;
  this.neighborLeft.right = leftNeighborImpact;
};

let lookupImpact = function(shape, orientation, side) {
  // this will be an index, must return Y (if this shape has a line connecting to that side), N (no line connecting to that side)
}

Tadpole.prototype.setShapeAndOrientation = function(constraints) {
  let topConstraintMatches = tileOptions["top"][constraints[0]];
  let rightConstraintMatches = tileOptions["right"][constraints[1]];
  let bottomConstraintMatches = tileOptions["bottom"][constraints[2]];
  let leftConstraintMatches = tileOptions["left"][constraints[3]];

  let verticalMatches = intersection_destructive(topConstraintMatches, bottomConstraintMatches);
  let horizontalMatches = intersection_destructive(leftConstraintMatches, rightConstraintMatches);
  let matchAllConstraints = intersection_destructive(verticalMatches, horizontalMatches);

  let shapeAndOrientation = matchAllConstraints.sample();
  let this.shape = shapeAndOrientation[0];
  let this.orientation = shapeAndOrientation[1];
};

let intersection_destructive = function(a, b) {
  var result = [];
  while( a.length > 0 && b.length > 0 ) {
     if      (a[0] < b[0] ){ a.shift(); }
     else if (a[0] > b[0] ){ b.shift(); }
     else {
       result.push(a.shift());
       b.shift();
     }
  }
  return result;
};

let tileOptions = {
  "top": {"n": [], "u": tileOptions["all"], "y": [["spoke", "top"],["arc", "right"],["arc", "bottom"],["line", "vertical"],["doubleArc", "top"],["doubleArc", "right"],["doubleArc", "left"],["quadArc", "all"]]},
  "right": [["spoke", "right"],["arc", "bottom"],["arc", "left"],["line", "horizontal"],["doubleArc", "top"],["doubleArc", "right"],["doubleArc", "bottom"],["quadArc", "all"]],
  "bottom": [["spoke", "bottom"],["arc", "top"],["arc", "left"],["line", "vertical"],["doubleArc", "right"],["doubleArc", "bottom"],["doubleArc", "left"],["quadArc", "all"]],
  "left": [["spoke", "left"],["arc", "top"],["arc", "right"],["line", "horizontal"],["doubleArc", "top"],["doubleArc", "bottom"],["doubleArc", "left"],["quadArc", "all"]],
  "all": [["spoke", "top"],["spoke", "right"],["spoke", "bottom"],["spoke", "left"],["arc", "top"],["arc", "right"],["arc", "bottom"],["arc", "left"],["line", "horizontal"],["line", "vertical"],["doubleArc", "top"],["doubleArc", "right"],["doubleArc", "bottom"],["doubleArc", "left"],["quadArc", "all"]]
};

module.exports = Tadpole;<|endoftext|>


<commit_before>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var key, x = 0;

            for (key in gamesData.games) {
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
 //             gamesToHtml += "" + gamesData.games[x].start_date + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
//                  table :vote    ---> votes!!!
//                  (integer :day :not-null) - äänestyspäivä
//                  (integer :index :not-null) - viestin numero #
//                  (varchar :voter 40 :not-null) - äänestäjä
//                  (varchar :target 40)))) - äänestyksen kohde
    "use strict";
    var req = new XMLHttpRequest();
    var address = "/game/" + id;
    req.open("GET", address, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            for (var i = 0; i < gameData.players.length; i++) {
                gameToHtml += "
" + gameData.players[i].name + "
";
            }

            var firstNewDayVote = false;
            var currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "

";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted
";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!
";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "
";
                }
            }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

//                            [b]Bill Murray (8):[/b] Holyflare, Eden1892, rsoultin, Superbia, Vivax, Breshke, raynpelikoneet, Palmar
//                            [b]Vivax (7):[/b] [s]Holyflare[/s], Artanis[Xp], [s]Damdred[/s], LightningStrike, sicklucker, Toadesstern, Trfel, ExO_,                             [s]rsoultin[/s], [s]Palmar[/s], Damdred
//                            [b]LightningStrike (3):[/b] Bill Murray, [s]Toadesstern[/s], FecalFeast, [s]raynpelikoneet[/s], [s]Vivax[/s], Onegu
//                            [b]Toadesstern (1):[/b] [s]Palmar[/s], [s]Artanis[Xp][/s], [s]raynpelikoneet[/s], [s]Vivax[/s], VisceraEyes,         //                              [s]Palmar[/s]
//                            [b]sicklucker (1):[/b] [s]Eden1892[/s], [s]Holyflare[/s], [s]rsoultin[/s], [s]Alakaslam[/s], [s]Superbia[/s],         //                              Alakaslam, [s]Eden1892[/s], [s]Breshke[/s]
//                            [b]raynpelikoneet (0):[/b] [s]Holyflare[/s], [s]Damdred[/s], [s]rsoultin[/s], [s]Trfel[/s], [s]ExO_[/s], [s]Damdred[/s]
//                            [b]Artanis[Xp] (0):[/b] [s]Toadesstern[/s], [s]Eden1892[/s], [s]VisceraEyes[/s], [s]Eden1892[/s]
//                            [b]Eden1892 (0):[/b] [s]Fecalfeast[/s], [s]Onegu[/s], [s]Bill Murray[/s], [s]ExO[/s]
//                            [b]Damdred (0):[/b] [s]raynpelikoneet[/s], [s]sicklucker[/s], [s]Artanis[Xp][/s]
//                            [b]Superbia (0):[/b] [s]Eden1892[/s]
//                            [b]VisceraEyes (0):[/b] [s]Artanis[Xp][/s]
//                            [b]Alakaslam (0):[/b] [s]Holyflare[/s], [s]Artanis[/s], [s]sicklucker[/s], [s]Eden1892[/s]
//                            [b]ExO_ (0):[/b] [s]Eden1892[/s]
//                            [b]Palmar (0):[/b] [s]Toadesstern[/s], [s]Toadesstern[/s], [s]Bill Murray[/s]
//                            [b]Trfel (0):[/b] [s]Artanis[/s], [s]Superbia[/s], [s]Eden1892[/s]
//                            [b]Holyflare (0):[/b] [s]Alakaslam[/s]
//
//                            [b]Not Voting (0):[/b]

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<commit_msg>gameview now shows game address and hosts as well<commit_after>function centerWindow() {
    "use strict";
    var centeredWidth = $('.centered').width() / 2,
        centeredHeight = $('.centered').height() / 2;
    $('.centered').css({ 'margin-left' : -centeredWidth , 'margin-top' : -centeredHeight });
}

function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var key, x = 0;

            for (key in gamesData.games) {
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
 //             gamesToHtml += "" + gamesData.games[x].start_date + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    var createGame = document.getElementById("creategame");
    document.getElementById("index").className += ' hidden';
    createGame.className = createGame.className.replace( /(?:^|\s)hidden(?!\S)/g , '' );

    centerWindow();
}

function hideCreateGame() {
    "use strict";
    document.getElementById("creategame").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

function showGame(id) {
//                  table :vote    ---> votes!!!
//                  (integer :day :not-null) - äänestyspäivä
//                  (integer :index :not-null) - viestin numero #
//                  (varchar :voter 40 :not-null) - äänestäjä
//                  (varchar :target 40)))) - äänestyksen kohde
    "use strict";
    var req = new XMLHttpRequest();
    var address = "/game/" + id;
    req.open("GET", address, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            gameToHtml += "Hosts";

            for (var i = 0; i < gameData.hosts.length; i++) {
                gameToHtml += "
" + gameData.hosts[i] + "
";
            }

            gameToHtml += "
Players";

            for (var i = 0; i < gameData.players.length; i++) {
                gameToHtml += "
" + gameData.players[i].name + "
";
            }

            var firstNewDayVote = false;
            var currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "

";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted
";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!
";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "
";
                }
            }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

//                            [b]Bill Murray (8):[/b] Holyflare, Eden1892, rsoultin, Superbia, Vivax, Breshke, raynpelikoneet, Palmar
//                            [b]Vivax (7):[/b] [s]Holyflare[/s], Artanis[Xp], [s]Damdred[/s], LightningStrike, sicklucker, Toadesstern, Trfel, ExO_,                             [s]rsoultin[/s], [s]Palmar[/s], Damdred
//                            [b]LightningStrike (3):[/b] Bill Murray, [s]Toadesstern[/s], FecalFeast, [s]raynpelikoneet[/s], [s]Vivax[/s], Onegu
//                            [b]Toadesstern (1):[/b] [s]Palmar[/s], [s]Artanis[Xp][/s], [s]raynpelikoneet[/s], [s]Vivax[/s], VisceraEyes,         //                              [s]Palmar[/s]
//                            [b]sicklucker (1):[/b] [s]Eden1892[/s], [s]Holyflare[/s], [s]rsoultin[/s], [s]Alakaslam[/s], [s]Superbia[/s],         //                              Alakaslam, [s]Eden1892[/s], [s]Breshke[/s]
//                            [b]raynpelikoneet (0):[/b] [s]Holyflare[/s], [s]Damdred[/s], [s]rsoultin[/s], [s]Trfel[/s], [s]ExO_[/s], [s]Damdred[/s]
//                            [b]Artanis[Xp] (0):[/b] [s]Toadesstern[/s], [s]Eden1892[/s], [s]VisceraEyes[/s], [s]Eden1892[/s]
//                            [b]Eden1892 (0):[/b] [s]Fecalfeast[/s], [s]Onegu[/s], [s]Bill Murray[/s], [s]ExO[/s]
//                            [b]Damdred (0):[/b] [s]raynpelikoneet[/s], [s]sicklucker[/s], [s]Artanis[Xp][/s]
//                            [b]Superbia (0):[/b] [s]Eden1892[/s]
//                            [b]VisceraEyes (0):[/b] [s]Artanis[Xp][/s]
//                            [b]Alakaslam (0):[/b] [s]Holyflare[/s], [s]Artanis[/s], [s]sicklucker[/s], [s]Eden1892[/s]
//                            [b]ExO_ (0):[/b] [s]Eden1892[/s]
//                            [b]Palmar (0):[/b] [s]Toadesstern[/s], [s]Toadesstern[/s], [s]Bill Murray[/s]
//                            [b]Trfel (0):[/b] [s]Artanis[/s], [s]Superbia[/s], [s]Eden1892[/s]
//                            [b]Holyflare (0):[/b] [s]Alakaslam[/s]
//
//                            [b]Not Voting (0):[/b]

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    document.getElementById("index").className += ' hidden';
    document.getElementById("gameview").className =
    document.getElementById("gameview").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
}

function hideGame() {
    "use strict";
    document.getElementById("gameview").className += ' hidden';
    document.getElementById("index").className =
    document.getElementById("index").className.replace
      ( /(?:^|\s)hidden(?!\S)/g , '' );
    window.location.hash = "";
}

requestData();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
    Text,
    View,
    ListView
} from 'react-native';
import { connect } from 'react-redux';
import _ from 'lodash';
import ListItem from './ListItemComponent';

class DayView extends Component {
    componentWillMount() {
        this.createDataSource(this.props);
    }

    componentWillReceiveProps(nextProps) {
        // nextProps are the next set of props that this component
        // will be rendered with
        // this.props is still the old set of props

        this.createDataSource(nextProps);
    }

    createDataSource({ events }) {
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });

        this.dataSource = ds.cloneWithRows(events);
    }

    renderRow(event) {
        let masterdataJSON = JSON.parse(this.props.masterdata);
        let eventJSON = JSON.parse(event);

        let eventName = _.find(masterdataJSON["programs"][this.props.program]["courses"], { 'course': eventJSON["course"] })["shortname"];
        let eventRoom = eventJSON["rooms"][0];
        let eventLecturers = [];
        for (let lecturer in eventJSON["lecturers"]) {
            eventLecturers.push(_.get(masterdataJSON["persons"], eventJSON["lecturers"][lecturer])["name"]);
        }
        eventLecturers = JSON.stringify(eventLecturers);
        let eventNote = eventJSON["note"];

        return <ListItem eventName={eventName} eventRoom={eventRoom} eventLecturers={eventLecturers} eventNote={eventNote} />;
    }

    render() {
        return (
            <View>
                <View style={styles.header}>
                    <Text style={styles.headerText}>{this.props.day}</Text>
                </View>
                <View>
                    <ListView
                        enableEmptySections
                        dataSource={this.dataSource}
                        renderRow={this.renderRow.bind(this)}
                    />
                </View>
            </View>
        );
    }
}

const styles = {
    header: {
        alignItems: "center",
        backgroundColor: "#F6F6F6",
        padding: 10
    },
    headerText: {
        fontSize: 20,
        fontWeight: "bold"
    }
};

const mapStateToProps = state => {
    return {
        program: state.login.program
    }
};

export default connect(mapStateToProps, {})(DayView);
<commit_msg>Flexed every component in the 'DayView' to make the 'DaySwitcher' component display correctly<commit_after>import React, { Component } from 'react';
import {
    Text,
    View,
    ListView
} from 'react-native';
import { connect } from 'react-redux';
import _ from 'lodash';
import ListItem from './ListItemComponent';

class DayView extends Component {
    componentWillMount() {
        this.createDataSource(this.props);
    }

    componentWillReceiveProps(nextProps) {
        this.createDataSource(nextProps);
    }

    createDataSource({ events }) {
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });

        this.dataSource = ds.cloneWithRows(events);
    }

    renderRow(event) {
        let masterdataJSON = JSON.parse(this.props.masterdata);
        let eventJSON = JSON.parse(event);

        let eventName = _.find(masterdataJSON["programs"][this.props.program]["courses"], { 'course': eventJSON["course"] })["shortname"];
        let eventRoom = eventJSON["rooms"][0];
        let eventLecturers = [];
        for (let lecturer in eventJSON["lecturers"]) {
            eventLecturers.push(_.get(masterdataJSON["persons"], eventJSON["lecturers"][lecturer])["name"]);
        }
        eventLecturers = JSON.stringify(eventLecturers);
        let eventNote = eventJSON["note"];

        return <ListItem eventName={eventName} eventRoom={eventRoom} eventLecturers={eventLecturers} eventNote={eventNote} />;
    }

    render() {
        return (
            <View style={styles.flex}>
                <View style={styles.header}>
                    <Text style={styles.headerText}>{this.props.day}</Text>
                </View>
                <View style={styles.flex}>
                    <ListView
                        enableEmptySections
                        dataSource={this.dataSource}
                        renderRow={this.renderRow.bind(this)}
                        style={styles.flex}
                    />
                </View>
            </View>
        );
    }
}

const styles = {
    header: {
        alignItems: "center",
        backgroundColor: "#F6F6F6",
        padding: 10
    },
    headerText: {
        fontSize: 20,
        fontWeight: "bold"
    },
    flex: {
        flex: 1
    }
};

const mapStateToProps = state => {
    return {
        program: state.login.program
    }
};

export default connect(mapStateToProps, {})(DayView);
<|endoftext|>


<commit_before>var { fork } = require('child_process')
var fs = require('fs')
var Rx = require('rxjs')

function Task(fn) {
    return Task.create(fn)
}
Task.createTaskManager = function createTaskManager(modulePath, args, options) {
    return new Promise((resolve, reject) => {
        fs.access(modulePath, err => {
            if (err) return reject(err)
            var task = Task.instantiate(modulePath, args, options)
            resolve(task)
        })
    })
}
Task.instantiate = function instantiate(modulePath, args, options) {
    var child = fork(modulePath, args, options)

    //child.on('error', err => console.error(child.pid, err))
    //child.on('exit', (code, signal) => console.log(child.pid, 'exited', code, signal))

    var send = (type, payload) => sendToProcess(child, type, payload)
    var command = cmd => send('COMMAND', cmd)

    child.execute = async () => {
        await command('EXECUTE')
        return child.onResponse
    }
    child.set = async function set(key, value) {
        return await send('SET', {
            key, value
        })
    }
    child.terminate = async () => {
        return await command('TERMINATE')
    }
    child.onResponse = (() => {
        return new Promise((resolve, reject) => {
            function resolveOnReturn(msg) {
                switch (msg.type) {
                    case 'RESOLVE': {
                        child.response = msg.payload
                        return resolve(msg.payload)
                    }
                    case 'REJECT': {
                        return reject(rebuildError(msg.payload))
                    }
                    default: return
                }
            }
            child.on('message', resolveOnReturn)
        })
    })()

    return child
}
Task.create = function create(fn) {
    var mainFn = fn
    var dataValues = {}

    var onMessage = Rx.Observable.fromEvent(process, 'message')
    var onCommand = onMessage.filter(action => action.type === 'COMMAND')
    var onSet = onMessage.filter(action => action.type === 'SET').map(action => action.payload)

    var disconnect = (function makeSubs() {
        var subs = [
            onCommand.subscribe(action => {
                handleCommand(action)
            }),
            onSet.subscribe(data => {
                dataValues[data.key] = data.value
            })
        ]
        return () => subs.map(sub => sub.unsubscribe())
    })()

    function execute() {
        return new Promise((resolve, reject) => {
            try {
                resolve(mainFn())
            } catch (err) {
                reject(err)
            }
        }).catch(err => {
            console.error('mainFn()', 'error')
            disconnect()
            reject(err)
        })
    }
    function resolve(data) {
        return sendToProcess(process, 'RESOLVE', data)
    }
    function reject(err) {
        var { name, message, stack } = err
        return sendToProcess(process, 'REJECT', {
            name, message, stack
        })
    }

    function handleCommand(action) {
        var { type, payload } = action
        if (payload === 'EXECUTE') return execute()
        if (payload === 'TERMINATE') return process.exit(0)
    }

    return {
        get: key => key ? dataValues[key] : dataValues,
        main: fn => mainFn = fn,
        message: msg => sendToProcess(process, 'MESSAGE', msg),
        resolve,
        reject,
        disconnect
    }
}

function sendToProcess(process, type, payload) {
    return new Promise((resolve, reject) => {
        process.send({
            type,
            payload
        }, err => err ? reject(err) : resolve())
    })
}

module.exports = Task

function rebuildError(err) {
    var error = new Error()
    error.name = err.name
    error.message = err.message
    error.stack = err.stack
    return error
}<commit_msg>reorder code<commit_after>var { fork } = require('child_process')
var fs = require('fs')
var Rx = require('rxjs')

function Task(fn) {
    return Task.create(fn)
}
Task.createTaskManager = function createTaskManager(modulePath, args, options) {
    return new Promise((resolve, reject) => {
        fs.access(modulePath, err => {
            if (err) return reject(err)
            var task = Task.instantiate(modulePath, args, options)
            resolve(task)
        })
    })
}
Task.instantiate = function instantiate(modulePath, args, options) {
    var child = fork(modulePath, args, options)

    //child.on('error', err => console.error(child.pid, err))
    //child.on('exit', (code, signal) => console.log(child.pid, 'exited', code, signal))

    var send = (type, payload) => sendToProcess(child, type, payload)
    var command = cmd => send('COMMAND', cmd)

    child.execute = async () => {
        await command('EXECUTE')
        return child.onResponse
    }
    child.set = async function set(key, value) {
        return await send('SET', {
            key, value
        })
    }
    child.terminate = async () => {
        return await command('TERMINATE')
    }
    child.onResponse = (() => {
        return new Promise((resolve, reject) => {
            function resolveOnReturn(msg) {
                switch (msg.type) {
                    case 'RESOLVE': {
                        child.response = msg.payload
                        return resolve(msg.payload)
                    }
                    case 'REJECT': {
                        return reject(rebuildError(msg.payload))
                    }
                    default: return
                }
            }
            child.on('message', resolveOnReturn)
        })
    })()

    return child
}
Task.create = function create(fn) {
    var mainFn = fn
    var dataValues = {}

    var COM = {
        message: msg => sendToProcess(process, 'MESSAGE', msg),
        resolve: data => sendToProcess(process, 'RESOLVE', data),
        reject: err => {
            var { name, message, stack } = err
            return sendToProcess(process, 'REJECT', {
                name, message, stack
            })
        }
    }

    var onMessage = Rx.Observable.fromEvent(process, 'message')
    var onCommand = onMessage.filter(action => action.type === 'COMMAND').map(action => action.payload)
    var onSet = onMessage.filter(action => action.type === 'SET').map(action => action.payload)

    var disconnect = (function makeSubs() {
        var subs = [
            onCommand.subscribe(cmd => {
                switch (cmd) {
                    case 'EXECUTE':
                        return execute()
                    case 'TERMINATE':
                        return process.exit(0)
                }
            }),
            onSet.subscribe(data => {
                dataValues[data.key] = data.value
            })
        ]
        return () => subs.map(sub => sub.unsubscribe())
    })()

    function execute() {
        return new Promise((resolve, reject) => {
            try {
                resolve(mainFn())
            } catch (err) {
                reject(err)
            }
        }).catch(err => {
            disconnect()
            COM.reject(err)
        })
    }

    return {
        get: key => key ? dataValues[key] : dataValues,
        main: fn => mainFn = fn,
        message: COM.message,
        resolve: COM.resolve,
        reject: COM.reject,
        disconnect
    }
}

function sendToProcess(process, type, payload) {
    return new Promise((resolve, reject) => {
        process.send({
            type,
            payload
        }, err => err ? reject(err) : resolve())
    })
}

module.exports = Task

function rebuildError(err) {
    var error = new Error()
    error.name = err.name
    error.message = err.message
    error.stack = err.stack
    return error
}<|endoftext|>


<commit_before>const max = process.argv[2];
let FizzBuzz = {
  [Symbol.iterator]() {
    let num = 1;
    return {
      next() {
        let value = num;
        if (value % 15 === 0) {
          value = 'FizzBuzz';
        } else if (value % 3 === 0) {
          value = 'Fizz';
        } else if (value % 5 === 0) {
          value = 'Buzz';
        }
        num++;
        if (num <= max)  return { done: false, value: value };
        return { done: true };
      }
    }
  }
}

for (var n of FizzBuzz) {
  console.log(n);
}

<commit_msg>Fix fizzbuzz's termination condition.<commit_after>const max = process.argv[2];
let FizzBuzz = {
  [Symbol.iterator]() {
    let num = 1;
    return {
      next() {
        let value = num;
        if (value % 15 === 0) {
          value = 'FizzBuzz';
        } else if (value % 3 === 0) {
          value = 'Fizz';
        } else if (value % 5 === 0) {
          value = 'Buzz';
        }
        if (num <= max)  return { done: false, value: value };
        num++;
        return { done: true };
      }
    }
  }
}

for (var n of FizzBuzz) {
  console.log(n);
}

<|endoftext|>


<commit_before>/*jshint evil: false, strict: false, undef: true, white: false, plusplus:false, node:true */

var path = require('path');
var _ = require('underscore');
var style = require('../colors');

function log() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('  ');
    console.log.apply(console, args);
}

function printObject(prefix, obj) {
    var names = Object.keys(obj);
    names.forEach(function(name) {
        var value = obj[name];
        if(typeof value === 'undefined') {
            return;
        }
        log(prefix,style.bold(name),':',value);
        //replace prefix by same amount of spaces
        prefix = Array(prefix.length + 1).join(" ");
    });
}

module.exports = function(trimBody_optional) {
    //true by default
    var trimBody = (_.isNull(trimBody_optional) || _.isUndefined(trimBody_optional)) ? true : trimBody_optional.toLowerCase() === 'true';

    function getTrimmedBody(body) {
        var maxlen = 500;
        var shouldTrim = trimBody && !!body && body.length > maxlen;
        if(typeof body === 'string') {
            if(shouldTrim) {
                body = body.substr(0,maxlen) + '...';
            } else {
                return body;
            }
        }
        else if(Buffer.isBuffer(body)) {
            if(shouldTrim) {
                return 'binary buffer: ' + body.slice(0, maxlen).toString('hex') + '...';
            } else {
                return 'binary buffer: ' + body.toString('hex');
            }
        }
        return body;
    }

    function printRequest(req) {
        var requestDescription = _.extend({}, req.headers, {body: getTrimmedBody(req.body)});
        printObject('==>', requestDescription);
    }

    function printResponse(res) {
        var responseDescription = _.extend({status: res.statusCode}, res.headers, {body: getTrimmedBody(res.body)});
        printObject('<==', responseDescription);
    }

    return {
        runStarted: function(testCaseCount) {

        },
        testCaseStarted: function(testCase, file) {
            console.log('Running', path.basename(file));
        },
        testStarted: function(testCase, test, description, index) {
            this.startStep(' * ' + description);
        },
        testFailed: function(testCase, test, err, index) {
            this.endStep(false);
            process.stdout.write('   ' + err.message);
            if(typeof err.actual !== 'undefined' && typeof err.actual !== 'object' && err.expected) {
                process.stdout.write(', expected ' + err.expected + ' but got ' + err.actual);
            }
            process.stdout.write('\n');
            if(test.line) {
                log('have a look at', test.line);
            }
            if(err.request) {
                printRequest(err.request);
            }
            if(err.response) {
                printResponse(err.response);
            }
        },
        testSucceeded: function(testCase, test, description, index) {
            this.endStep(true);
        },
        testCaseEnded: function(testCase, file, hasFailures) {},
        runEnded: function(testCaseCount, failureCount, totalTestCount) {
            if(failureCount === 0) {
                console.log(style.bold('ran ' + totalTestCount + ' tests in ' +
                        testCaseCount + ' test cases, all ran with ' +
                        style.green('SUCCESS')));
            } else {
                console.log(style.bold('ran ' + testCaseCount + ' test cases, ' +
                        failureCount + ' of them ' + style.red('FAILED')));
            }
        },
        startStep: function(description) {
            process.stdout.write(description + ' ... ');
        },
        endStep: function(success) {
            if(!success) {
                console.log(style.red(style.bold('FAILED')));
            } else {
                console.log(style.green(style.bold('OK!')));
            }
        },
        write: function(message) {
            console.log(message);
        }
    };
};<commit_msg>making the console formatter better readable<commit_after>/*jshint evil: false, strict: false, undef: true, white: false, plusplus:false, node:true */

var path = require('path');
var _ = require('underscore');
var style = require('../colors');

function log() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('  ');
    console.log.apply(console, args);
}

function printObject(prefix, obj) {
    var names = Object.keys(obj);
    names.forEach(function(name) {
        var value = obj[name];
        if(typeof value === 'undefined') {
            return;
        }
        log(prefix,style.bold(name),':',value);
        //replace prefix by same amount of spaces
        prefix = Array(prefix.length + 1).join(" ");
    });
}

module.exports = function(trimBody_optional) {
    //true by default
    var trimBody = (_.isNull(trimBody_optional) || _.isUndefined(trimBody_optional)) ? true : trimBody_optional.toLowerCase() === 'true';

    function getTrimmedBody(body) {
        var maxlen = 500;
        var shouldTrim = trimBody && !!body && body.length > maxlen;
        if(typeof body === 'string') {
            if(shouldTrim) {
                body = body.substr(0,maxlen) + '...';
            } else {
                return body;
            }
        }
        else if(Buffer.isBuffer(body)) {
            if(shouldTrim) {
                return 'binary buffer: ' + body.slice(0, maxlen).toString('hex') + '...';
            } else {
                return 'binary buffer: ' + body.toString('hex');
            }
        }
        return body;
    }

    function printRequest(req) {
        var requestDescription = _.extend({}, req.headers, {body: getTrimmedBody(req.body)});
        printObject('==>', requestDescription);
    }

    function printResponse(res) {
        var responseDescription = _.extend({status: res.statusCode}, res.headers, {body: getTrimmedBody(res.body)});
        printObject('<==', responseDescription);
    }

    return {
        runStarted: function(testCaseCount) {

        },
        testCaseStarted: function(testCase, file) {
            console.log(style.cyan("-=>"),'Running', path.basename(file));
        },
        testStarted: function(testCase, test, description, index) {
            this.startStep(style.yellow('    * ') + description);
        },
        testFailed: function(testCase, test, err, index) {
            this.endStep(false);
            process.stdout.write('   ' + err.message);
            if(typeof err.actual !== 'undefined' && typeof err.actual !== 'object' && err.expected) {
                process.stdout.write(', expected ' + err.expected + ' but got ' + err.actual);
            }
            process.stdout.write('\n');
            if(test.line) {
                log('have a look at', test.line);
            }
            if(err.request) {
                printRequest(err.request);
            }
            if(err.response) {
                printResponse(err.response);
            }
        },
        testSucceeded: function(testCase, test, description, index) {
            this.endStep(true);
        },
        testCaseEnded: function(testCase, file, hasFailures) {},
        runEnded: function(testCaseCount, failureCount, totalTestCount) {
            if(failureCount === 0) {
                console.log(style.bold('ran ' + totalTestCount + ' tests in ' +
                        testCaseCount + ' test cases, all ran with ' +
                        style.green('SUCCESS')));
            } else {
                console.log(style.bold('ran ' + testCaseCount + ' test cases, ' +
                        failureCount + ' of them ' + style.red('FAILED')));
            }
        },
        startStep: function(description) {
            process.stdout.write(description + ' ... ');
        },
        endStep: function(success) {
            if(!success) {
                console.log(style.red(style.bold('FAILED')));
            } else {
                console.log(style.green(style.bold('OK!')));
            }
        },
        write: function(message) {
            console.log(message);
        }
    };
};<|endoftext|>


<commit_before>'use babel';

import path from 'path';
import readline from 'readline';
import { spawn } from 'child_process';
import SearchEnv from './search-env';
import SearchIndexer from './search-indexer';

const LINE_REGEX = /^([^:]+):(\d+):(.+)$/;

class SearchInstance {
    constructor(regex, options, iterator) {
        this.regex = regex;
        this.options = options;
        this.iterator = iterator;
        this.promise = new Promise(resolve => {
            this.resolve = resolve;
            this.initResultExclusions();
            this.runSearch();
        });
        this.promise.cancel = () => this.cancel();
    }

    initResultExclusions() {
        if (atom.config.get('core.excludeVcsIgnoredPaths')) {
            this.projectRepos = atom.project.getRepositories().filter(repo => repo);
        }
        let ignoredFiles = atom.config.get('core.ignoredNames');
        if (ignoredFiles && ignoredFiles.length) {
            this.ignoredFilesRegex = new RegExp('[\\\\/]' + ignoredFiles.map(f => '(' + this.pathToRegex(f) + ')').join('|'));
        }
    }

    runSearch() {
        let flags = SearchEnv.opts;
        if (SearchEnv.engine !== 'pt') {
            flags.push('-n');
        }
        if (this.regex.ignoreCase) {
            flags.unshift('-i');
        }
        flags.push(this.regex.source);
        if (SearchEnv.engine === 'csearch') {
            flags.unshift('-f', this.getSearchPathsRegex());
            this.ensureIndexExists()
                .then(() => this.startCSearch(flags))
                .catch(() => this.resolve());
        } else {
            flags = flags.concat(this.getSearchPaths(true));
            this.startCSearch(flags);
        }
    }

    ensureIndexExists() {
        const idx = SearchIndexer.instance;
        return idx.wait.then(() => {
            if (this.cancelled) {
                throw 'Search cancelled';
            }
            return idx.listIndexed().then(indexed => {
                let newPaths = atom.project.getPaths().filter(path => indexed.indexOf(path) < 0);
                if (!newPaths.length) {
                    return;
                }
                if (SearchEnv.debugMode) {
                    console.log('[csearch] missing paths', newPaths);
                }
                idx.reindex();
                return new Promise((resolve, reject) => {
                    idx.once('finished', success => {
                        if (!success) {
                            this.iterator(undefined, { message: 'Project indexing error' });
                            return reject();
                        }
                        resolve();
                    });
                });
            }).catch(err => {
                if (SearchEnv.debugMode) {
                    console.error('[csearch] cindex error', err);
                }
                this.iterator(undefined, { message: 'Project indexing error: ' + err });
                throw err;
            })
        });
    }

    getSearchPaths(join) {
        let projectPaths = atom.project.getPaths();
        let searchPaths = this.options && this.options.paths || [];
        if (!searchPaths || !searchPaths.length) {
            return projectPaths;
        }
        let foundPaths = [];
        searchPaths.forEach(searchPath => {
            if (!searchPath) {
                return;
            }
            if (path.isAbsolute(searchPath)) {
                return foundPaths.push(searchPath);
            }
            let firstFolder = searchPath.split(/[\\\/]/)[0];
            let matchingProjectPaths = projectPaths.filter(pp => pp.endsWith(firstFolder));
            if (matchingProjectPaths.length) {
                foundPaths = foundPaths.concat(matchingProjectPaths
                    .map(pp => path.join(pp, searchPath.substr(firstFolder.length + 1)))
                );
            } else {
                foundPaths = foundPaths.concat(projectPaths
                    .map(pp => join ? path.join(pp, searchPath) : (pp + '*' + searchPath))
                );
            }
        });
        return foundPaths;
    }

    getSearchPathsRegex() {
        return '^(' + this.getSearchPaths().map(p => '(' + this.pathToRegex(p) + ')').join('|') + ')';
    }

    pathToRegex(path) {
        return path
            .replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
            .replace(/\*+/g, '.*')
            .replace(/"/g, '""');
    }

    startCSearch(flags) {
        if (this.cancelled) {
            return this.resolve();
        }
        const opts = SearchEnv.engine === 'csearch' && SearchEnv.indexBasePath ?
            { env: { CSEARCHINDEX: path.join(SearchEnv.indexBasePath, 'csearchindex'), PATH: process.env.PATH } } : undefined;
        this.csearch = spawn(SearchEnv.commandPath, flags, opts);
        if (SearchEnv.debugMode) {
            console.log('[csearch] started', SearchEnv.commandPath, flags);
        }
        this.csearch.unref();
        this.stdoutLineReader = readline.createInterface({ input: this.csearch.stdout });
        this.stderrLineReader = readline.createInterface({ input: this.csearch.stderr });
        this.stdoutLineReader.on('line', line => this.onOutLine(line));
        this.stderrLineReader.on('line', line => this.onErrLine(line));
        this.csearch.on('close', code => this.onCSearchExit(code));
        this.csearch.on('error', err => this.onCSearchError(err, path.basename(SearchEnv.commandPath)));
    }

    onCSearchExit(code) {
        if (SearchEnv.debugMode) {
            console.log('[csearch] exit code', code);
        }
        if (this.fileRes) {
            this.iterator(this.fileRes);
            this.fileRes = null;
        }
        if (this.stdoutLineReader) {
            this.stdoutLineReader.close();
            this.stdoutLineReader = null;
        }
        if (this.stderrLineReader) {
            this.stderrLineReader.close();
            this.stderrLineReader = null;
        }
        this.csearch = null;
        this.resolve();
    }

    onCSearchError(err, cmd) {
        if (err && err.code === 'ENOENT') {
            const links = {
                rg: 'https://github.com/BurntSushi/ripgrep#installation',
                csearch: 'https://github.com/sidiandi/codesearch#readme',
                pt: 'https://github.com/monochromegane/the_platinum_searcher#installation',
                ag: 'https://github.com/ggreer/the_silver_searcher#installing'
            };
            const link = links[cmd];
            atom.notifications.addError('`' + cmd + '` command not found, is it installed?  \n' +
                'You can change the path in atom-codesearch package settings.', {
                dismissable: true,
                buttons: link ? [{
                    text: 'How to install?',
                    onDidClick: function() {
                        require('electron').shell.openExternal(link);
                    }
                }] : null
            });
            this.iterator(undefined, { message: 'Search error: `csearch` command not found' });
        }
    }

    onOutLine(line) {
        const match = LINE_REGEX.exec(line);
        if (!match) {
            return;
        }
        const [, filePath, lineNumber, lineText] = match;
        if (lineText) {
            if (this.ignoredFilesRegex && this.ignoredFilesRegex.test(filePath)) {
                return;
            }
            if (this.projectRepos && this.projectRepos.some(repo => repo.isPathIgnored(filePath))) {
                return;
            }
            if (this.fileRes && this.fileRes.filePath !== filePath) {
                this.iterator(this.fileRes);
                this.fileRes = null;
            }
            if (!this.fileRes) {
                this.fileRes = {
                    filePath: filePath,
                    matches: []
                };
            }
            const row = lineNumber - 1;
            let lineMatch;
            do {
                lineMatch = this.regex.exec(lineText);
                if (lineMatch) {
                    this.fileRes.matches.push({
                        lineText: lineText,
                        lineTextOffset: 0,
                        matchText: lineMatch[0],
                        range: [[row, lineMatch.index],
                            [row, lineMatch.index + lineMatch[0].length]]
                    });
                }
            } while (lineMatch);
        }
    }

    onErrLine(line) {
        if (line.startsWith('open') && line.endsWith('no such file or directory')) {
            return;
        }
        if (SearchEnv.debugMode) {
            console.error('[csearch] error', line);
        }
        this.iterator(undefined, { message: line });
    }

    cancel() {
        this.cancelled = true;
        if (this.stdoutLineReader) {
            this.stdoutLineReader.removeAllListeners('line');
        }
        if (this.csearch) {
            this.csearch.kill();
        }
    }
}

export default SearchInstance;
<commit_msg>fix error message<commit_after>'use babel';

import path from 'path';
import readline from 'readline';
import { spawn } from 'child_process';
import SearchEnv from './search-env';
import SearchIndexer from './search-indexer';

const LINE_REGEX = /^([^:]+):(\d+):(.+)$/;

class SearchInstance {
    constructor(regex, options, iterator) {
        this.regex = regex;
        this.options = options;
        this.iterator = iterator;
        this.promise = new Promise(resolve => {
            this.resolve = resolve;
            this.initResultExclusions();
            this.runSearch();
        });
        this.promise.cancel = () => this.cancel();
    }

    initResultExclusions() {
        if (atom.config.get('core.excludeVcsIgnoredPaths')) {
            this.projectRepos = atom.project.getRepositories().filter(repo => repo);
        }
        let ignoredFiles = atom.config.get('core.ignoredNames');
        if (ignoredFiles && ignoredFiles.length) {
            this.ignoredFilesRegex = new RegExp('[\\\\/]' + ignoredFiles.map(f => '(' + this.pathToRegex(f) + ')').join('|'));
        }
    }

    runSearch() {
        let flags = SearchEnv.opts;
        if (SearchEnv.engine !== 'pt') {
            flags.push('-n');
        }
        if (this.regex.ignoreCase) {
            flags.unshift('-i');
        }
        flags.push(this.regex.source);
        if (SearchEnv.engine === 'csearch') {
            flags.unshift('-f', this.getSearchPathsRegex());
            this.ensureIndexExists()
                .then(() => this.startCSearch(flags))
                .catch(() => this.resolve());
        } else {
            flags = flags.concat(this.getSearchPaths(true));
            this.startCSearch(flags);
        }
    }

    ensureIndexExists() {
        const idx = SearchIndexer.instance;
        return idx.wait.then(() => {
            if (this.cancelled) {
                throw 'Search cancelled';
            }
            return idx.listIndexed().then(indexed => {
                let newPaths = atom.project.getPaths().filter(path => indexed.indexOf(path) < 0);
                if (!newPaths.length) {
                    return;
                }
                if (SearchEnv.debugMode) {
                    console.log('[csearch] missing paths', newPaths);
                }
                idx.reindex();
                return new Promise((resolve, reject) => {
                    idx.once('finished', success => {
                        if (!success) {
                            this.iterator(undefined, { message: 'Project indexing error' });
                            return reject();
                        }
                        resolve();
                    });
                });
            }).catch(err => {
                if (SearchEnv.debugMode) {
                    console.error('[csearch] cindex error', err);
                }
                this.iterator(undefined, { message: 'Project indexing error: ' + err });
                throw err;
            })
        });
    }

    getSearchPaths(join) {
        let projectPaths = atom.project.getPaths();
        let searchPaths = this.options && this.options.paths || [];
        if (!searchPaths || !searchPaths.length) {
            return projectPaths;
        }
        let foundPaths = [];
        searchPaths.forEach(searchPath => {
            if (!searchPath) {
                return;
            }
            if (path.isAbsolute(searchPath)) {
                return foundPaths.push(searchPath);
            }
            let firstFolder = searchPath.split(/[\\\/]/)[0];
            let matchingProjectPaths = projectPaths.filter(pp => pp.endsWith(firstFolder));
            if (matchingProjectPaths.length) {
                foundPaths = foundPaths.concat(matchingProjectPaths
                    .map(pp => path.join(pp, searchPath.substr(firstFolder.length + 1)))
                );
            } else {
                foundPaths = foundPaths.concat(projectPaths
                    .map(pp => join ? path.join(pp, searchPath) : (pp + '*' + searchPath))
                );
            }
        });
        return foundPaths;
    }

    getSearchPathsRegex() {
        return '^(' + this.getSearchPaths().map(p => '(' + this.pathToRegex(p) + ')').join('|') + ')';
    }

    pathToRegex(path) {
        return path
            .replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
            .replace(/\*+/g, '.*')
            .replace(/"/g, '""');
    }

    startCSearch(flags) {
        if (this.cancelled) {
            return this.resolve();
        }
        const opts = SearchEnv.engine === 'csearch' && SearchEnv.indexBasePath ?
            { env: { CSEARCHINDEX: path.join(SearchEnv.indexBasePath, 'csearchindex'), PATH: process.env.PATH } } : undefined;
        this.csearch = spawn(SearchEnv.commandPath, flags, opts);
        if (SearchEnv.debugMode) {
            console.log('[csearch] started', SearchEnv.commandPath, flags);
        }
        this.csearch.unref();
        this.stdoutLineReader = readline.createInterface({ input: this.csearch.stdout });
        this.stderrLineReader = readline.createInterface({ input: this.csearch.stderr });
        this.stdoutLineReader.on('line', line => this.onOutLine(line));
        this.stderrLineReader.on('line', line => this.onErrLine(line));
        this.csearch.on('close', code => this.onCSearchExit(code));
        this.csearch.on('error', err => this.onCSearchError(err, path.basename(SearchEnv.commandPath)));
    }

    onCSearchExit(code) {
        if (SearchEnv.debugMode) {
            console.log('[csearch] exit code', code);
        }
        if (this.fileRes) {
            this.iterator(this.fileRes);
            this.fileRes = null;
        }
        if (this.stdoutLineReader) {
            this.stdoutLineReader.close();
            this.stdoutLineReader = null;
        }
        if (this.stderrLineReader) {
            this.stderrLineReader.close();
            this.stderrLineReader = null;
        }
        this.csearch = null;
        this.resolve();
    }

    onCSearchError(err, cmd) {
        if (err && err.code === 'ENOENT') {
            const links = {
                rg: 'https://github.com/BurntSushi/ripgrep#installation',
                csearch: 'https://github.com/sidiandi/codesearch#readme',
                pt: 'https://github.com/monochromegane/the_platinum_searcher#installation',
                ag: 'https://github.com/ggreer/the_silver_searcher#installing'
            };
            const link = links[cmd];
            atom.notifications.addError('`' + cmd + '` command not found, is it installed?  \n' +
                'You can change the path in atom-codesearch package settings.', {
                dismissable: true,
                buttons: link ? [{
                    text: 'How to install?',
                    onDidClick: function() {
                        require('electron').shell.openExternal(link);
                    }
                }] : null
            });
            this.iterator(undefined, { message: 'Search error: `' + cmd + '` command not found' });
        }
    }

    onOutLine(line) {
        const match = LINE_REGEX.exec(line);
        if (!match) {
            return;
        }
        const [, filePath, lineNumber, lineText] = match;
        if (lineText) {
            if (this.ignoredFilesRegex && this.ignoredFilesRegex.test(filePath)) {
                return;
            }
            if (this.projectRepos && this.projectRepos.some(repo => repo.isPathIgnored(filePath))) {
                return;
            }
            if (this.fileRes && this.fileRes.filePath !== filePath) {
                this.iterator(this.fileRes);
                this.fileRes = null;
            }
            if (!this.fileRes) {
                this.fileRes = {
                    filePath: filePath,
                    matches: []
                };
            }
            const row = lineNumber - 1;
            let lineMatch;
            do {
                lineMatch = this.regex.exec(lineText);
                if (lineMatch) {
                    this.fileRes.matches.push({
                        lineText: lineText,
                        lineTextOffset: 0,
                        matchText: lineMatch[0],
                        range: [[row, lineMatch.index],
                            [row, lineMatch.index + lineMatch[0].length]]
                    });
                }
            } while (lineMatch);
        }
    }

    onErrLine(line) {
        if (line.startsWith('open') && line.endsWith('no such file or directory')) {
            return;
        }
        if (SearchEnv.debugMode) {
            console.error('[csearch] error', line);
        }
        this.iterator(undefined, { message: line });
    }

    cancel() {
        this.cancelled = true;
        if (this.stdoutLineReader) {
            this.stdoutLineReader.removeAllListeners('line');
        }
        if (this.csearch) {
            this.csearch.kill();
        }
    }
}

export default SearchInstance;
<|endoftext|>


<commit_before>import React from 'react';
import {FormGroup as BootstrapFormGroup, HelpBlock, ControlLabel, Col} from 'react-bootstrap';

const FormGroupStacked = React.createClass({

    propTypes: {
        error: React.PropTypes.string,
        touched: React.PropTypes.bool,
        displayName: React.PropTypes.string,
        name: React.PropTypes.string,
        help: React.PropTypes.string
    },

    render: function () {

        let {
            error,
            touched,
            displayName,
            name,
            children,
            help,
            innerSize,
            className
        } = this.props;

        let formGroupProps = {
            className,
            validationState: error && touched ? 'error' : null
        };

        innerSize = innerSize || 12;
        let controlLabel = displayName != undefined ? <ControlLabel>{ displayName || name }</ControlLabel> : null;
        let helpText = (touched ? error : '') || help;
        let helpBlock = helpText ? <HelpBlock>{helpText}</HelpBlock> : null;

        return <BootstrapFormGroup {...formGroupProps}>
            <Col md={innerSize} className="no-padding-col">
                { controlLabel }
                { children }
                { helpBlock }
            </Col>

        </BootstrapFormGroup>
    }
});

export default FormGroupStacked;<commit_msg>Start es6-refactor: - Replaced React.createClass for es6 class and reduce methods in render to extract them as es6 class properties in order to get better readability. - Refactor in FormGroupStacked<commit_after>import React, { Component, PropTypes } from 'react';
import { FormGroup as BootstrapFormGroup } from 'react-bootstrap';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import Col from 'react-bootstrap/lib/Col';

class FormGroupStacked extends Component {
    static propTypes = {
        error: PropTypes.string,
        touched: PropTypes.bool,
        displayName: PropTypes.string,
        name: PropTypes.string,
        help: PropTypes.string
    };

    getControlLabel = () => {
        let { displayName, name } = this.props;

        if (displayName != undefined) {
            return (
                <ControlLabel>
                    { displayName || name }
                </ControlLabel>
            )
        } else {
            return null;
        }
    };

    getHelpBlock = () => {
        let { error, touched, help } = this.props;
        let helpText = (touched ? error : '') || help;

        if (helpText) {
            return (
                <HelpBlock>
                    {helpText}
                </HelpBlock>
            )
        } else {
            return null;
        }
    };

    render() {
        let { error, touched, children, innerSize, className } = this.props;
        let validationState =  error && touched ? 'error' : null;
        let formGroupProps = { className, validationState};

        return <BootstrapFormGroup {...formGroupProps}>
            <Col className="no-padding-col" md={innerSize || 12}>
                { this.getControlLabel() }
                { children }
                { this.getHelpBlock() }
            </Col>

        </BootstrapFormGroup>
    }
}

export default FormGroupStacked;<|endoftext|>


<commit_before>/**
 * @fileoverview Provides a feature popup directive.
 */
goog.provide('app.FeaturePopupController');
goog.provide('app.featurePopupDirective');

goog.require('app');
goog.require('app.Mymaps');

/**
 * @param {string} appFeaturePopupTemplateUrl URL to the directive template.
 * @return {angular.Directive} The Directive Definition Object.
 * @ngInject
 */
app.featurePopupDirective = function(appFeaturePopupTemplateUrl) {
  return {
    restrict: 'A',
    scope: {
      'feature': '=appFeaturePopupFeature'
    },
    controller: 'AppFeaturePopupController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appFeaturePopupTemplateUrl
  };
};

app.module.directive('appFeaturePopup', app.featurePopupDirective);

/**
 * @constructor
 * @param {angular.Scope} $scope Scope.
 * @param {angular.$sce} $sce Angular $sce service
 * @param {app.FeaturePopup} appFeaturePopup The feature popup service.
 * @param {app.DrawnFeatures} appDrawnFeatures Drawn features service.
 * @param {app.Mymaps} appMymaps Mymaps service.
 * @param {app.SelectedFeatures} appSelectedFeatures Selected features service.
 * @export
 * @ngInject
 */
app.FeaturePopupController = function($scope, $sce, appFeaturePopup,
    appDrawnFeatures, appMymaps, appSelectedFeatures) {

  /**
   * @type {ol.Collection.<ol.Feature>}
   * @private
   */
  this.selectedFeatures_ = appSelectedFeatures;

  /**
   * @type {app.Mymaps}
   * @private
   */
  this.appMymaps_ = appMymaps;

  /**
   * @type {ol.Feature}
   * @export
   */
  this.feature;

  /**
   * @type {angular.$sce}
   * @private
   */
  this.sce_ = $sce;

  /**
   * @type {boolean}
   * @export
   */
  this.editingAttributes = false;

  /**
   * @type {boolean}
   * @export
   */
  this.editingStyle = false;

  /**
   * @type {boolean}
   * @export
   */
  this.deletingFeature = false;

  /**
   * @type {string}
   * @export
   */
  this.tempName = '';

  /**
   * @type {string}
   * @export
   */
  this.tempDesc = '';

  /**
   * @type {app.DrawnFeatures}
   * @private
   */
  this.drawnFeatures_ = appDrawnFeatures;

  this.appFeaturePopup_ = appFeaturePopup;

  $scope.$watch(goog.bind(function() {
    return this.editingAttributes;
  }, this), goog.bind(function(newVal) {
    if (newVal) {
      this.initForm_();
    }
  }, this));

  $scope.$watch(goog.bind(function() {
    return this.feature;
  }, this), goog.bind(function(newVal) {
    this.editingAttributes = false;
    this.editingStyle = false;
    this.deletingFeature = false;
  }, this));
};

/**
 */
app.FeaturePopupController.prototype.close = function() {
  this.appFeaturePopup_.hide();
};

/**
 * @return {boolean} return true if is editable by the user.
 * @export
 */
app.FeaturePopupController.prototype.isEditable = function() {
  if (goog.isDef(this.feature) &&
      this.feature.get('__source__') == 'mymaps') {
    return this.appMymaps_.isEditable();
  }
  return true;
};

/**
 * Inits the attributes form (ie. gets the name and description from feature).
 * @private
 */
app.FeaturePopupController.prototype.initForm_ = function() {
  this.tempName = /** @type {string} */ (this.feature.get('name'));
  this.tempDesc = /** @type {string} */ (this.feature.get('description'));
};

/**
 * Puts the temporary edited name and description back to the feature.
 * @export
 */
app.FeaturePopupController.prototype.validateModifications = function() {
  this.feature.set('name', this.tempName);
  this.feature.set('description', this.tempDesc);
  this.drawnFeatures_.saveFeature(this.feature);
  this.editingAttributes = false;
};

/**
 * Puts the temporary edited name and description back to the feature.
 * @export
 */
app.FeaturePopupController.prototype.deleteFeature = function() {
  this.appFeaturePopup_.hide();
  this.selectedFeatures_.remove(this.feature);
  this.drawnFeatures_.remove(this.feature);
  this.deletingFeature = false;
};

/**
 * Returns a trusted html content.
 * @param {?string|undefined} content content to be trusted.
 * @return {*} the trusted content.
 * @export
 */
app.FeaturePopupController.prototype.trustAsHtml = function(content) {
  if (!goog.isDefAndNotNull(content)) {
    content = '';
  }
  return this.sce_.trustAsHtml(content);
};

app.module.controller('AppFeaturePopupController', app.FeaturePopupController);
<commit_msg>Final dot is missing<commit_after>/**
 * @fileoverview Provides a feature popup directive.
 */
goog.provide('app.FeaturePopupController');
goog.provide('app.featurePopupDirective');

goog.require('app');
goog.require('app.Mymaps');

/**
 * @param {string} appFeaturePopupTemplateUrl URL to the directive template.
 * @return {angular.Directive} The Directive Definition Object.
 * @ngInject
 */
app.featurePopupDirective = function(appFeaturePopupTemplateUrl) {
  return {
    restrict: 'A',
    scope: {
      'feature': '=appFeaturePopupFeature'
    },
    controller: 'AppFeaturePopupController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appFeaturePopupTemplateUrl
  };
};

app.module.directive('appFeaturePopup', app.featurePopupDirective);

/**
 * @constructor
 * @param {angular.Scope} $scope Scope.
 * @param {angular.$sce} $sce Angular $sce service.
 * @param {app.FeaturePopup} appFeaturePopup The feature popup service.
 * @param {app.DrawnFeatures} appDrawnFeatures Drawn features service.
 * @param {app.Mymaps} appMymaps Mymaps service.
 * @param {app.SelectedFeatures} appSelectedFeatures Selected features service.
 * @export
 * @ngInject
 */
app.FeaturePopupController = function($scope, $sce, appFeaturePopup,
    appDrawnFeatures, appMymaps, appSelectedFeatures) {

  /**
   * @type {ol.Collection.<ol.Feature>}
   * @private
   */
  this.selectedFeatures_ = appSelectedFeatures;

  /**
   * @type {app.Mymaps}
   * @private
   */
  this.appMymaps_ = appMymaps;

  /**
   * @type {ol.Feature}
   * @export
   */
  this.feature;

  /**
   * @type {angular.$sce}
   * @private
   */
  this.sce_ = $sce;

  /**
   * @type {boolean}
   * @export
   */
  this.editingAttributes = false;

  /**
   * @type {boolean}
   * @export
   */
  this.editingStyle = false;

  /**
   * @type {boolean}
   * @export
   */
  this.deletingFeature = false;

  /**
   * @type {string}
   * @export
   */
  this.tempName = '';

  /**
   * @type {string}
   * @export
   */
  this.tempDesc = '';

  /**
   * @type {app.DrawnFeatures}
   * @private
   */
  this.drawnFeatures_ = appDrawnFeatures;

  this.appFeaturePopup_ = appFeaturePopup;

  $scope.$watch(goog.bind(function() {
    return this.editingAttributes;
  }, this), goog.bind(function(newVal) {
    if (newVal) {
      this.initForm_();
    }
  }, this));

  $scope.$watch(goog.bind(function() {
    return this.feature;
  }, this), goog.bind(function(newVal) {
    this.editingAttributes = false;
    this.editingStyle = false;
    this.deletingFeature = false;
  }, this));
};

/**
 */
app.FeaturePopupController.prototype.close = function() {
  this.appFeaturePopup_.hide();
};

/**
 * @return {boolean} return true if is editable by the user.
 * @export
 */
app.FeaturePopupController.prototype.isEditable = function() {
  if (goog.isDef(this.feature) &&
      this.feature.get('__source__') == 'mymaps') {
    return this.appMymaps_.isEditable();
  }
  return true;
};

/**
 * Inits the attributes form (ie. gets the name and description from feature).
 * @private
 */
app.FeaturePopupController.prototype.initForm_ = function() {
  this.tempName = /** @type {string} */ (this.feature.get('name'));
  this.tempDesc = /** @type {string} */ (this.feature.get('description'));
};

/**
 * Puts the temporary edited name and description back to the feature.
 * @export
 */
app.FeaturePopupController.prototype.validateModifications = function() {
  this.feature.set('name', this.tempName);
  this.feature.set('description', this.tempDesc);
  this.drawnFeatures_.saveFeature(this.feature);
  this.editingAttributes = false;
};

/**
 * Puts the temporary edited name and description back to the feature.
 * @export
 */
app.FeaturePopupController.prototype.deleteFeature = function() {
  this.appFeaturePopup_.hide();
  this.selectedFeatures_.remove(this.feature);
  this.drawnFeatures_.remove(this.feature);
  this.deletingFeature = false;
};

/**
 * Returns a trusted html content.
 * @param {?string|undefined} content content to be trusted.
 * @return {*} the trusted content.
 * @export
 */
app.FeaturePopupController.prototype.trustAsHtml = function(content) {
  if (!goog.isDefAndNotNull(content)) {
    content = '';
  }
  return this.sce_.trustAsHtml(content);
};

app.module.controller('AppFeaturePopupController', app.FeaturePopupController);
<|endoftext|>


<commit_before>'use strict';
var qs = require('querystring');
var twilio = require('twilio');
var cookie = require('cookie');
var crypto = require('crypto');
var encryptKey = "s0m3Rand0mStr!ng"; // this should be put into a config var, env var
var encryptStandard = "aes256";

module.exports = function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    var formValues = qs.parse(req.body);
    req.session = getCookieSession(context, req);
    //context.log(formValues);
    var twiml = new twilio.TwimlResponse();
    var text = formValues.Body;

    // Is this a response to a queue-triggered SMS? If so, "session" is stored in queue record
    // this needs to be refactored so it is more readable... TODO...
    if (isResponseYes(text) || isResponseNo(text) && !(req.session.askedQueued || req.session.askedReminder)) {
        context.log("lookup phone # in queued database table and add info to session var");
        // if no info is found in database nothing gets added to the session var
    }

    // If found a citation from a previous text... check the response for yes
    //      if yes add reminder to database and text info about reminder
    //      if no (or anything besides yes) text info about where they can find more information
    if (req.session.askedReminder) {
        context.log("has req.session.askedReminder")
        if (isResponseYes(text)) {
            context.log("has req.session.askedReminder and texted Yes")
            // db.addReminder({
            //     caseId: req.session.match.id,
            //     phone: req.body.From,
            //     originalCase: JSON.stringify(req.session.match)
            // }, function (err, data) {
            //     if (err) {
            //         rollbar.handleError(err, req);
            //     }
            // });

            // twiml.sms('Sounds good. We will attempt to text you a courtesy reminder the day before your hearing date. Note that court schedules frequently change. You should always confirm your hearing date and time by going to ' + process.env.COURT_PUBLIC_URL);
            // req.session.askedReminder = false;
            // res.send(twiml.toString());
        }
        else {
            context.log("has req.session.askedQueued and did NOT answer yes")
            // twiml.sms('OK. You can always go to ' + process.env.COURT_PUBLIC_URL + ' for more information about your case and contact information.');
            // req.session.askedReminder = false;
            // res.send(twiml.toString());
        }
        context.done(null, res);
    }

    // If did not find a citation from a previous text... check the response for yes previouse text searched for a citation but did not finddid not find citation but gave an option to send reminder if citation shows up later...
    if (req.session.askedQueued) {
        context.log("has req.session.askedQueued")
        if (isResponseYes(text)) {
            context.log("has req.session.askedQueued and texted Yes")
            // db.addQueued({
            //     citationId: req.session.citationId,
            //     phone: req.body.From
            // }, function (err, data) {
            //     if (err) {
            //         next(err);
            //     }
            //     twiml.sms('OK. We will keep checking for up to ' + process.env.QUEUE_TTL_DAYS + ' days. You can always go to ' + process.env.COURT_PUBLIC_URL + ' for more information about your case and contact information.');
            //     req.session.askedQueued = false;
            //     res.send(twiml.toString());
            // });
        }
        else {
            context.log("has req.session.askedQueued and did NOT answer yes")
            // twiml.sms('OK. You can always go to ' + process.env.COURT_PUBLIC_URL + ' for more information about your case and contact information.');
            // req.session.askedQueued = false;
            // res.send(twiml.toString());
        }
        context.done(null, res);
    }

    // First text from number, lookup citation and send response based on results
    Context.log("First text from phone number");
    // db.findCitation(text, function (err, results) {
    //     // If we can't find the case, or find more than one case with the citation
    //     // number, give an error and recommend they call in.
    //     if (!results || results.length === 0 || results.length > 1) {
    //         var correctLengthCitation = 6 <= text.length && text.length <= 25;
    //         if (correctLengthCitation) {
    //             twiml.sms('Could not find a case with that number. It can take several days for a case to appear in our system. Would you like us to keep checking for the next ' + process.env.QUEUE_TTL_DAYS + ' days and text you if we find it? (reply YES or NO)');

    //             req.session.askedQueued = true;
    //             req.session.citationId = text;
    //         } else {
    //             twiml.sms('Couldn\'t find your case. Case identifier should be 6 to 25 numbers and/or letters in length.');
    //         }
    //     } else {
    //         var match = results[0];
    //         var name = cleanupName(match.defendant);
    //         var datetime = dates.fromUtc(match.date);

    //         twiml.sms('Found a case for ' + name + ' scheduled on ' + datetime.format("ddd, MMM Do") + ' at ' + datetime.format("h:mm A") + ', at ' + match.room + '. Would you like a courtesy reminder the day before? (reply YES or NO)');

    //         req.session.match = match;
    //         req.session.askedReminder = true;
    //     }

    //     res.send(twiml.toString());
    // });

    twiml.message('You said: ' + formValues.Body);

    //var encryptSessionString = encrypt(JSON.stringify(req.session));
    // var setCookie = cookie.serialize("session", encryptSessionString, {
    //     secure: true
    // });
    var sessionString = JSON.stringify(req.session);
    var setCookie = cookie.serialize("session", sessionString, {
        secure: true
    });

    var res = {
        status: 200,
        body: twiml.toString(),
        headers: {
            'Content-Type': 'application/xml',
            'Set-Cookie': setCookie
        },
        isRaw: true
    };

    context.done(null, res);
};

function getCookieSession(context, req) {
    var cookies = cookie.parse(req.headers.cookie || "", {
        secure: true
    });
    var cookieSession;

    if (cookies.session) {
        context.log("session cookie found");
        // var decryptCookie = decrypt(cookies.session);
        // context.log("session cookie : " + decryptCookie);

        // cookieSession = JSON.parse(decryptCookie);
        context.log("session cookie : " + cookies.session);
        cookieSession = JSON.parse(cookies.session);
    }
    else { // set first time cookie for Twilio
        context.log("no cookie name found");
        cookieSession = { askQueued: false, name: "xbob" };
    }

    return cookieSession;
}

function isResponseYes(text) {
    text = text.toUpperCase().trim();
    return (text === 'YES' || text === 'YEA' || text === 'YUP' || text === 'Y');
}

function isResponseNo(text) {
    text = text.toUpperCase().trim();
    return (text === 'NO' || text === 'N');
}

function encrypt(text) {
    var cipher = crypto.createCipher(encryptStandard, encryptKey)
    var crypted = cipher.update(text, 'utf8', 'hex')
    crypted += cipher.final('hex');
    return crypted;
}

function decrypt(text) {
    var decipher = crypto.createDecipher(encryptStandard, encryptKey)
    var dec = decipher.update(text, 'hex', 'utf8')
    dec += decipher.final('utf8');
    return dec;
}

<commit_msg>more testing added twilio messages to courtbot logic<commit_after>'use strict';
var qs = require('querystring');
var twilio = require('twilio');
var cookie = require('cookie');
var crypto = require('crypto');
var encryptKey = "s0m3Rand0mStr!ng"; // this should be put into a config var, env var
var encryptStandard = "aes256";

module.exports = function (context, req) {
    var res;
    var twiml = new twilio.TwimlResponse();
    context.log('JavaScript HTTP trigger function processed a request.');
    var formValues = qs.parse(req.body);
    req.session = getCookieSession(context, req);
    //context.log(formValues);
    var text = formValues.Body;
    context.log("req.body.Body text: " + text);

    // Is this a response to a queue-triggered SMS? If so, "session" is stored in queue record
    // this needs to be refactored so it is more readable... TODO...
    if (isResponseYes(text) || isResponseNo(text) && !(req.session.askedQueued || req.session.askedReminder)) {
        context.log("lookup phone # in queued database table and add info to session var");
        // if no info is found in database nothing gets added to the session var
    }

    // If found a citation from a previous text... check the response for yes
    //      if yes add reminder to database and text info about reminder
    //      if no (or anything besides yes) text info about where they can find more information
    if (req.session.askedReminder) {
        context.log("has req.session.askedReminder")
        if (isResponseYes(text)) {
            context.log("has req.session.askedReminder and texted Yes")

            // db.addReminder({
            //     caseId: req.session.match.id,
            //     phone: req.body.From,
            //     originalCase: JSON.stringify(req.session.match)
            // }, function (err, data) {
            //     if (err) {
            //         rollbar.handleError(err, req);
            //     }
            // });

            twiml.sms('Sounds good. We will attempt to text you a courtesy reminder the day before your hearing date. Note that court schedules frequently change. You should always confirm your hearing date and time by going to ' + process.env.COURT_PUBLIC_URL);
        }
        else {
            context.log("has req.session.askedQueued and did NOT answer yes")
            twiml.sms('OK. You can always go to ' + process.env.COURT_PUBLIC_URL + ' for more information about your case and contact information.');
        }
        req.session.askedReminder = false; //reset var to false
        res = generateResponse(req, twiml);
        return context.done(null, res);
    }

    // If did not find a citation from a previous text... check the response for yes previouse text searched for a citation but did not finddid not find citation but gave an option to send reminder if citation shows up later...
    if (req.session.askedQueued) {
        context.log("has req.session.askedQueued")
        if (isResponseYes(text)) {
            context.log("has req.session.askedQueued and texted Yes")
            twiml.sms('OK. We will keep checking for up to ' + process.env.QUEUE_TTL_DAYS + ' days. You can always go to ' + process.env.COURT_PUBLIC_URL + ' for more information about your case and contact information.');

            // db.addQueued({
            //     citationId: req.session.citationId,
            //     phone: req.body.From
            // }, function (err, data) {
            //     if (err) {
            //         next(err);
            //     }
            //     twiml.sms('OK. We will keep checking for up to ' + process.env.QUEUE_TTL_DAYS + ' days. You can always go to ' + process.env.COURT_PUBLIC_URL + ' for more information about your case and contact information.');
            // });
        }
        else {
            context.log("has req.session.askedQueued and did NOT answer yes")
            twiml.sms('OK. You can always go to ' + process.env.COURT_PUBLIC_URL + ' for more information about your case and contact information.');
        }
        req.session.askedQueued = false; //reset var to false
        res = generateResponse(req, twiml);
        return context.done(null, res);
    }

    // First text from number, lookup citation and send response based on results
    context.log("First text from phone number");
    // db.findCitation(text, function (err, results) {
    //     // If we can't find the case, or find more than one case with the citation
    //     // number, give an error and recommend they call in.
    //     if (!results || results.length === 0 || results.length > 1) {
    //         var correctLengthCitation = 6 <= text.length && text.length <= 25;
    //         if (correctLengthCitation) {
    //             twiml.sms('Could not find a case with that number. It can take several days for a case to appear in our system. Would you like us to keep checking for the next ' + process.env.QUEUE_TTL_DAYS + ' days and text you if we find it? (reply YES or NO)');

    //             req.session.askedQueued = true;
    //             req.session.citationId = text;
    //         } else {
    //             twiml.sms('Couldn\'t find your case. Case identifier should be 6 to 25 numbers and/or letters in length.');
    //         }
    //     } else {
    //         var match = results[0];
    //         var name = cleanupName(match.defendant);
    //         var datetime = dates.fromUtc(match.date);

    //         twiml.sms('Found a case for ' + name + ' scheduled on ' + datetime.format("ddd, MMM Do") + ' at ' + datetime.format("h:mm A") + ', at ' + match.room + '. Would you like a courtesy reminder the day before? (reply YES or NO)');

    //         req.session.match = match;
    //         req.session.askedReminder = true;
    //     }

    //     res.send(twiml.toString());
    // });

    //var encryptSessionString = encrypt(JSON.stringify(req.session));
    // var setCookie = cookie.serialize("session", encryptSessionString, {
    //     secure: true
    // });
    var sessionString = JSON.stringify(req.session);
    var setCookie = cookie.serialize("session", sessionString, {
        secure: true
    });

    var res = {
        status: 200,
        body: twiml.toString(),
        headers: {
            'Content-Type': 'application/xml',
            'Set-Cookie': setCookie
        },
        isRaw: true
    };

    context.done(null, res);
};

function generateResponse(req, twiml) {
    var sessionString = JSON.stringify(req.session);
    var setCookie = cookie.serialize("session", sessionString, {
        secure: true
    });

    var res = {
        status: 200,
        body: twiml.toString(),
        headers: {
            'Content-Type': 'application/xml',
            'Set-Cookie': setCookie
        },
        isRaw: true
    };

    return res;
}

function getCookieSession(context, req) {
    var cookies = cookie.parse(req.headers.cookie || "", {
        secure: true
    });

    context.log("cookies: " + req.headers.cookie);
    var cookieSession;

    if (cookies.session) {
        context.log("session cookie found");
        // var decryptCookie = decrypt(cookies.session);
        // context.log("session cookie : " + decryptCookie);

        // cookieSession = JSON.parse(decryptCookie);
        context.log("session cookie : " + cookies.session);
        cookieSession = JSON.parse(cookies.session);
    }
    else { // set first time cookie for Twilio
        context.log("no cookie name found");
        cookieSession = {};
    }

    return cookieSession;
}

function isResponseYes(text) {
    text = text.toUpperCase().trim();
    return (text === 'YES' || text === 'YEA' || text === 'YUP' || text === 'Y');
}

function isResponseNo(text) {
    text = text.toUpperCase().trim();
    return (text === 'NO' || text === 'N');
}

function encrypt(text) {
    var cipher = crypto.createCipher(encryptStandard, encryptKey)
    var crypted = cipher.update(text, 'utf8', 'hex')
    crypted += cipher.final('hex');
    return crypted;
}

function decrypt(text) {
    var decipher = crypto.createDecipher(encryptStandard, encryptKey)
    var dec = decipher.update(text, 'hex', 'utf8')
    dec += decipher.final('utf8');
    return dec;
}

<|endoftext|>


<commit_before>'use strict';

var Chalk = require('chalk');
var Table = require('cli-table');
var Cvss = require('cvss');

module.exports = function (err, data, pkgPath) {

  var returnString = '';

  if (err) {
    if (data) {
      returnString += Chalk.red('(+) ') + 'Debug output: ' + JSON.stringify(Buffer.isBuffer(data) ? data.toString() : data) + '\n';
    }

    return returnString + Chalk.yellow('(+) ') + err;
  }

  var width = 80;
  if (process.stdout.isTTY) {
    width = (process.stdout.getWindowSize()[0] - 10) || 80;
  }
  if (data.length === 0) {

    return Chalk.green('(+)') + ' No known vulnerabilities found';
  }

  returnString += Chalk.red('(+) ') + data.length + ' vulnerabilities found\n';

  data.sort(function(a, b) {

    return b.cvss_score - a.cvss_score;
  }).forEach(function (finding) {

    var table = new Table({
      head: ['', finding.title],
      colWidths: [15, width - 15]
    });

    table.push(['Name', finding.module]);
    table.push(['CVSS', finding.cvss_score + ' (' + Cvss.getRating(finding.cvss_score) + ')']);
    table.push(['Installed', finding.version]);
    table.push(['Vulnerable', finding.vulnerable_versions === '<=99.999.99999' ? 'All' : finding.vulnerable_versions]);
    table.push(['Patched', finding.patched_versions === '<0.0.0' ? 'None' : finding.patched_versions]);
    table.push(['Path', finding.path.join(' > ')]);
    table.push(['More Info', finding.advisory]);

    returnString += table.toString() + '\n';
  });

  return returnString;
};
<commit_msg>Make sure the table width is a minimum width<commit_after>'use strict';

var Chalk = require('chalk');
var Table = require('cli-table');
var Cvss = require('cvss');

module.exports = function (err, data, pkgPath) {

  var returnString = '';

  if (err) {
    if (data) {
      returnString += Chalk.red('(+) ') + 'Debug output: ' + JSON.stringify(Buffer.isBuffer(data) ? data.toString() : data) + '\n';
    }

    return returnString + Chalk.yellow('(+) ') + err;
  }

  var width = 80;
  var colWidth = 15;
  if (process.stdout.isTTY) {
    width = process.stdout.getWindowSize()[0] - 10;
    if (!width || width <= colWidth) {
      width = 80;
    }
  }
  if (data.length === 0) {

    return Chalk.green('(+)') + ' No known vulnerabilities found';
  }

  returnString += Chalk.red('(+) ') + data.length + ' vulnerabilities found\n';

  data.sort(function(a, b) {

    return b.cvss_score - a.cvss_score;
  }).forEach(function (finding) {

    var table = new Table({
      head: ['', finding.title],
      colWidths: [colWidth, width - colWidth]
    });

    table.push(['Name', finding.module]);
    table.push(['CVSS', finding.cvss_score + ' (' + Cvss.getRating(finding.cvss_score) + ')']);
    table.push(['Installed', finding.version]);
    table.push(['Vulnerable', finding.vulnerable_versions === '<=99.999.99999' ? 'All' : finding.vulnerable_versions]);
    table.push(['Patched', finding.patched_versions === '<0.0.0' ? 'None' : finding.patched_versions]);
    table.push(['Path', finding.path.join(' > ')]);
    table.push(['More Info', finding.advisory]);

    returnString += table.toString() + '\n';
  });

  return returnString;
};
<|endoftext|>