<commit_before>var tuer = require('./app'),
Log = require('log'),
fs = require('fs'),
logpath = '/home/tuer2.0/error.log',
old = fs.readFileSync(logpath,'utf-8'),
stream = fs.createWriteStream(logpath),
log = new Log('error',stream);

process.on('uncaughtException',function(err){
    stream.write(old,'utf-8',function(){
        log.error(err);
    });
});

tuer.start({
    rootdir:'/home/tuer2.0/',
    port:3000,
    mport:3030,
    cookiepath:'tuer.me',
    host:'www.tuer.me',
    jshost:'js.tuer.me',
    csshost:'css.tuer.me',
    imagehost:'img.tuer.me',
    dbname:'node-mongo-tuer',
    dbhost:'127.0.0.1',
    dbport:10001,
    mhost:'m.tuer.me'
});

<commit_msg>fix path<commit_after>var tuer = require('./app'),
Log = require('log'),
fs = require('fs'),
logpath = __dirname+'/error.log',
old = fs.readFileSync(logpath,'utf-8'),
stream = fs.createWriteStream(logpath),
log = new Log('error',stream);

process.on('uncaughtException',function(err){
    stream.write(old,'utf-8',function(){
        log.error(err);
    });
});

tuer.start({
    rootdir:__dirname,
    port:3000,
    mport:3030,
    cookiepath:'tuer.me',
    host:'www.tuer.me',
    jshost:'js.tuer.me',
    csshost:'css.tuer.me',
    imagehost:'img.tuer.me',
    dbname:'node-mongo-tuer',
    dbhost:'127.0.0.1',
    dbport:10001,
    mhost:'m.tuer.me'
});

<|endoftext|>


<commit_before>'use strict';

function check_neighbor_match(position){
    var next_positions = [
      [-x_scaled_half, -y_scaled,],
      [-x_scaled, 0,],
      [-x_scaled_half, y_scaled,],
      [x_scaled_half, -y_scaled,],
      [x_scaled, 0,],
      [x_scaled_half, y_scaled,],
    ];
    for(var next_position in next_positions){
        if(position['y'] % y_scaled_double){
            next_positions[next_position][0] += x_scaled;
        }

        var new_next_position = select_hexagon(
          select_y_mod(
            position['x'] + next_positions[next_position][0],
            position['y'] + next_positions[next_position][1]
          ),
          position['y'] + next_positions[next_position][1]
        );
        for(var hexagon in hexagons){
            if(hexagons[hexagon]['x'] === new_next_position['x']
              && hexagons[hexagon]['y'] === new_next_position['y']
              && hexagons[hexagon]['color'] === players[player_ids[turn]]['color']){
                return true;
            }
        }
    }

    return false;
}

function conquer_hexagon(hexagon, playerid){
    playerid = playerid || player_ids[turn];

    if(hexagons[hexagon]['color'] !== players[playerid]['color']){
        if(hexagons[hexagon]['color'] === core_storage_data['default-color']){
            hexagons[hexagon]['color'] = players[playerid]['color'];
            players[playerid]['hexagons'] += 1;
            unclaimed -= 1;

        }else if(core_random_boolean()){
            var old_color = hexagons[hexagon]['color'];
            hexagons[hexagon]['color'] = players[playerid]['color'];
            players[playerid]['hexagons'] += 1;
            for(var player in players){
                if(old_color === players[player]['color']){
                    lose_hexagon(player);
                    break;
                }
            }
        }
    }
}

function create_hexagon(position, size){
    // Only create a hexagon if one doesn't already exist at this x,y.
    for(var hexagon in hexagons){
        if(hexagons[hexagon]['x'] === position['x']
          && hexagons[hexagon]['y'] === position['y']){
            return;
        }
    }

    hexagons.push({
      'color': core_storage_data['default-color'],
      'size': size,
      'x': position['x'],
      'y': position['y'],
    });
    unclaimed = hexagons.length;
}

function create_player(properties){
    if(player_count > hexagons.length - 1){
        return;
    }

    properties = properties || {};
    properties = {
      'ai': properties['ai'] || false,
      'color': properties['color'] || '#' + core_random_hex(),
      'done': false,
      'hexagons': 0,
      'name': '',
    };
    properties['name'] = (properties['ai']
      ? 'AI'
      : 'P')
      + properties['color'];

    players[player_count] = properties;
    player_ids.push(player_count);

    var hexagon = core_random_integer({
      'max': hexagons.length,
    });
    while(hexagons[hexagon]['color'] !== core_storage_data['default-color']){
        hexagon = core_random_integer({
          'max': hexagons.length,
        });
    }
    conquer_hexagon(
      hexagon,
      player_count
    );

    player_count += 1;
}

function draw_hexagon(x, y, size, color){
    if(y % hexagon_size){
        x += x_scaled_half;
    }

    var vertices = [];
    for(var i = 0; i < 6; i++){
        var angle = math_degrees_to_radians({
          'degrees': 30 + i * 60,
        });
        vertices.push({
          'type': i === 0
            ? 'moveTo'
            : 'lineTo',
          'x': x + Math.cos(angle) * size + canvas_x,
          'y': y + Math.sin(angle) * size + canvas_y,
        });
    }
    canvas_draw_path({
      'properties': {
        'fillStyle': color,
      },
      'vertices': vertices,
    });
}

function draw_logic(){
    // Save the current buffer state.
    canvas_buffer.save();

    // Translate to camera position.
    canvas_buffer.translate(
      camera['x'],
      camera['y']
    );

    // Draw selection if not AI turn.
    if(players[player_ids[turn]]
      && players[player_ids[turn]]['ai'] === false){
        draw_hexagon(
          core_mouse['x'],
          core_mouse['y'],
          core_storage_data['hexagon-size'] + 5,
          players[player_ids[turn]]['color']
        );
    }

    // Draw hexagons.
    for(var hexagon in hexagons){
        draw_hexagon(
          hexagons[hexagon]['x'],
          hexagons[hexagon]['y'],
          hexagons[hexagon]['size'],
          hexagons[hexagon]['color']
        );
    }

    // Restore the buffer state.
    canvas_buffer.restore();

    var x = 25;

    // Draw turn info.
    if(players[player_ids[turn]]){
        canvas_buffer.fillStyle = '#fff';
        canvas_buffer.fillText(
          'Turn#' + turns + turn_limit_string + ' ' + players[player_ids[turn]]['name'],
          0,
          x
        );
        x += 25;
    }

    if(unclaimed > 0){
        // Draw unclaimed hexagons.
        canvas_buffer.fillStyle = core_storage_data['default-color'],
        canvas_buffer.fillText(
          'Unclaimed:' + unclaimed,
          0,
          x
        );
        x += 25;
    }

    // Draw scoreboard.
    for(var player in scoreboard){
        if(!players[scoreboard[player]['id']]){
            continue;
        }

        canvas_buffer.fillStyle = players[scoreboard[player]['id']]['color'];
        canvas_buffer.fillText(
          players[scoreboard[player]['id']]['name']
            + (players[scoreboard[player]['id']]['done']
              ? '='
              : ':')
            + scoreboard[player]['hexagons'],
          0,
          x
        );
        x += 25;
    }

    // Draw winner.
    if(game_over){
        canvas_buffer.fillStyle = players[scoreboard[0]['id']]['color'];
        canvas_buffer.fillText(
          players[scoreboard[0]['id']]['name'] + ' wins!',
          0,
          x
        );
    }
}

function end_turn(){
    var over = true;
    for(var player in players){
        if(!players[player]['done']){
            over = false;
            break;
        }
    }
    if(over
      || turns >= core_storage_data['turn-limit']){
        game_over = true;
        return;
    }

    if(turn >= player_ids.length - 1){
        turn = 0;

    }else{
        turn += 1;
    }

    if(!players[player_ids[turn]]){
        end_turn();

    }else{
        turns += 1;
    }
}

function handle_ai_turn(){
    if(!players[player_ids[turn]]
      || !players[player_ids[turn]]['ai']
      || game_over){
        return;
    }

    if(!players[player_ids[turn]]['done']){
        var options = [];
        var options_used = true;
        for(var hexagon in hexagons){
            if(hexagons[hexagon]['color'] === players[player_ids[turn]]['color']){
                continue;
            }

            if(check_neighbor_match({
              'x': hexagons[hexagon]['x'],
              'y': hexagons[hexagon]['y'],
            })){
                if(hexagons[hexagon]['color'] === core_storage_data['default-color']){
                    conquer_hexagon(hexagon);
                    options_used = false;
                    break;

                }else{
                    options.push(hexagon);
                }
            }
        }
        if(options_used){
            if(options.length > 0){
                sort_random({
                  'array': options,
                });
                scoreboard_loop:
                for(var i = scoreboard.length; i--;){
                    if(!players[scoreboard[i]['id']]){
                        continue;
                    }

                    for(var option in options){
                        if(hexagons[options[option]]['color'] === players[scoreboard[i]['id']]['color']){
                            conquer_hexagon(options[option]);
                            break scoreboard_loop;
                        }
                    }
                }

            }else{
                players[player_ids[turn]]['done'] = true;
            }
        }
    }

    end_turn();
}

function logic(){
    // Move camera left.
    if(core_keys[65]['state']
      && camera['x'] < width_half){
        camera['x'] += core_storage_data['scroll-speed'];
    }

    // Move camera right.
    if(core_keys[68]['state']
      && camera['x'] > -width_half){
        camera['x'] -= core_storage_data['scroll-speed'];
    }

    // Move camera down.
    if(core_keys[83]['state']
      && camera['y'] > -height_half){
        camera['y'] -= core_storage_data['scroll-speed'];
    }

    // Move camera up.
    if(core_keys[87]['state']
      && camera['y'] < height_half){
        camera['y'] += core_storage_data['scroll-speed'];
    }

    handle_ai_turn();
    update_scoreboard();
}

function lose_hexagon(player){
    players[player]['hexagons'] -= 1;
    if(players[player]['hexagons'] <= 0){
        delete players[player];
        player_count -= 1;
    }
}

function repo_init(){
    core_repo_init({
      'info': 'New Game',
      'keybinds': {
        65: {},
        68: {},
        72: {
          'todo': function(){
              if(players[player_ids[turn]]
                && !players[player_ids[turn]]['ai']){
                  end_turn();
              }
          },
        },
        80: {
          'todo': function(){
              if(!game_over
                && players[player_ids[turn]]
                && !players[player_ids[turn]]['ai']){
                  for(var hexagon in hexagons){
                      if(!players[player_ids[turn]]){
                          break;
                        }
                      if(hexagons[hexagon]['color'] === players[player_ids[turn]]['color']){
                          hexagons[hexagon]['color'] = core_storage_data['default-color'];
                          lose_hexagon(player_ids[turn]);
                          unclaimed += 1;
                      }
                  }
                  for(var player in players){
                      players[player]['done'] = false;
                  }
                  end_turn();
              }
          },
        },
        83: {},
        87: {},
      },
      'menu': true,
      'mousebinds': {
        'mousedown': {
          'todo': function(event){
              if(canvas_mode <= 0
                || !players[player_ids[turn]]
                || players[player_ids[turn]]['ai']){
                  return;
              }

              var position = select_hexagon(
                core_mouse['x'],
                core_mouse['y']
              );

              // Check if a hexagon exists at this location
              //   with a different color.
              var target = false;
              for(var hexagon in hexagons){
                  if(hexagons[hexagon]['x'] === position['x']
                    && hexagons[hexagon]['y'] === position['y']
                    && hexagons[hexagon]['color'] !== players[player_ids[turn]]['color']){
                      target = hexagon;
                      break;
                  }
              }
              if(target === false){
                  return;
              }

              // Check if current player has a hexagon next to target hexagon.
              if(!check_neighbor_match({
                'x': hexagons[target]['x'],
                'y': hexagons[target]['y'],
              })){
                  return;
              }

              // Attempt to conquer the hexagon.
              conquer_hexagon(hexagon);

              end_turn();
          },
        },
        'mousemove': {
          'todo': function(){
              var x = core_mouse['x'] - canvas_x - camera['x'];
              var y = core_mouse['y'] - canvas_y - camera['y'];
              var position = select_hexagon(
                select_y_mod(
                  x,
                  y
                ),
                y
              );
              core_mouse['x'] = position['x'];
              core_mouse['y'] = position['y'];
          },
        },
      },
      'storage': {
        'ai': 4,
        'default-color': '#ffffff',
        'height': 500,
        'hexagon-size': 25,
        'hexagons': 150,
        'ms-per-frame': 1,
        'players': 1,
        'scroll-speed': 5,
        'turn-limit': Infinity,
        'width': 500,
      },
      'storage-menu': '<input id=ai>AI
<input id=default-color type=color>Default Color
<input id=height>Height
<input id=hexagons>Hexagons
<input id=hexagon-size>Hexagon Size
<input id=ms-per-frame>ms/Frame
<input id=players>Players
<input id=scroll-speed>Scroll Speed
<input id=turn-limit>Turn Limit
<input id=width>Width',
      'title': 'Hexagons-2D.htm',
    });
    canvas_init();
}

function select_hexagon(x, y){
    return {
      'x': Math.ceil((x - x_scaled_half) / x_scaled) * x_scaled,
      'y': Math.ceil((y - y_scaled_half) / y_scaled) * y_scaled,
    };
}

function select_y_mod(x, y, move){
    move = move || -(x_scaled_half);

    var y_mod = Math.abs(y % y_scaled_double);
    if(y_mod > y_scaled_half
      && y_mod < y_scaled * 1.5){
        x += move;
    }

    return x;
}

function update_scoreboard(){
    scoreboard = [];
    for(var player in players){
        scoreboard.push({
          'hexagons': players[player]['hexagons'],
          'id': player,
        });
    }
    sort_property({
      'array': scoreboard,
      'property': 'hexagons',
      'reverse': true,
    });
}

var camera = {};
var game_over = false;
var height_half = 0;
var hexagon_size = 0;
var hexagons = [];
var player_count = 0;
var player_ids = [];
var players = {};
var scoreboard = [];
var turn = 0;
var turn_limit_string = '';
var turns = 0;
var unclaimed = 0;
var width_half = 0;
var x_scaled = 0;
var x_scaled_half = 0;
var y_scaled = 0;
var y_scaled_double = 0;
var y_scaled_half = 0;
<commit_msg>made setmode links into buttons<commit_after>'use strict';

function check_neighbor_match(position){
    var next_positions = [
      [-x_scaled_half, -y_scaled,],
      [-x_scaled, 0,],
      [-x_scaled_half, y_scaled,],
      [x_scaled_half, -y_scaled,],
      [x_scaled, 0,],
      [x_scaled_half, y_scaled,],
    ];
    for(var next_position in next_positions){
        if(position['y'] % y_scaled_double){
            next_positions[next_position][0] += x_scaled;
        }

        var new_next_position = select_hexagon(
          select_y_mod(
            position['x'] + next_positions[next_position][0],
            position['y'] + next_positions[next_position][1]
          ),
          position['y'] + next_positions[next_position][1]
        );
        for(var hexagon in hexagons){
            if(hexagons[hexagon]['x'] === new_next_position['x']
              && hexagons[hexagon]['y'] === new_next_position['y']
              && hexagons[hexagon]['color'] === players[player_ids[turn]]['color']){
                return true;
            }
        }
    }

    return false;
}

function conquer_hexagon(hexagon, playerid){
    playerid = playerid || player_ids[turn];

    if(hexagons[hexagon]['color'] !== players[playerid]['color']){
        if(hexagons[hexagon]['color'] === core_storage_data['default-color']){
            hexagons[hexagon]['color'] = players[playerid]['color'];
            players[playerid]['hexagons'] += 1;
            unclaimed -= 1;

        }else if(core_random_boolean()){
            var old_color = hexagons[hexagon]['color'];
            hexagons[hexagon]['color'] = players[playerid]['color'];
            players[playerid]['hexagons'] += 1;
            for(var player in players){
                if(old_color === players[player]['color']){
                    lose_hexagon(player);
                    break;
                }
            }
        }
    }
}

function create_hexagon(position, size){
    // Only create a hexagon if one doesn't already exist at this x,y.
    for(var hexagon in hexagons){
        if(hexagons[hexagon]['x'] === position['x']
          && hexagons[hexagon]['y'] === position['y']){
            return;
        }
    }

    hexagons.push({
      'color': core_storage_data['default-color'],
      'size': size,
      'x': position['x'],
      'y': position['y'],
    });
    unclaimed = hexagons.length;
}

function create_player(properties){
    if(player_count > hexagons.length - 1){
        return;
    }

    properties = properties || {};
    properties = {
      'ai': properties['ai'] || false,
      'color': properties['color'] || '#' + core_random_hex(),
      'done': false,
      'hexagons': 0,
      'name': '',
    };
    properties['name'] = (properties['ai']
      ? 'AI'
      : 'P')
      + properties['color'];

    players[player_count] = properties;
    player_ids.push(player_count);

    var hexagon = core_random_integer({
      'max': hexagons.length,
    });
    while(hexagons[hexagon]['color'] !== core_storage_data['default-color']){
        hexagon = core_random_integer({
          'max': hexagons.length,
        });
    }
    conquer_hexagon(
      hexagon,
      player_count
    );

    player_count += 1;
}

function draw_hexagon(x, y, size, color){
    if(y % hexagon_size){
        x += x_scaled_half;
    }

    var vertices = [];
    for(var i = 0; i < 6; i++){
        var angle = math_degrees_to_radians({
          'degrees': 30 + i * 60,
        });
        vertices.push({
          'type': i === 0
            ? 'moveTo'
            : 'lineTo',
          'x': x + Math.cos(angle) * size + canvas_x,
          'y': y + Math.sin(angle) * size + canvas_y,
        });
    }
    canvas_draw_path({
      'properties': {
        'fillStyle': color,
      },
      'vertices': vertices,
    });
}

function draw_logic(){
    // Save the current buffer state.
    canvas_buffer.save();

    // Translate to camera position.
    canvas_buffer.translate(
      camera['x'],
      camera['y']
    );

    // Draw selection if not AI turn.
    if(players[player_ids[turn]]
      && players[player_ids[turn]]['ai'] === false){
        draw_hexagon(
          core_mouse['x'],
          core_mouse['y'],
          core_storage_data['hexagon-size'] + 5,
          players[player_ids[turn]]['color']
        );
    }

    // Draw hexagons.
    for(var hexagon in hexagons){
        draw_hexagon(
          hexagons[hexagon]['x'],
          hexagons[hexagon]['y'],
          hexagons[hexagon]['size'],
          hexagons[hexagon]['color']
        );
    }

    // Restore the buffer state.
    canvas_buffer.restore();

    var x = 25;

    // Draw turn info.
    if(players[player_ids[turn]]){
        canvas_buffer.fillStyle = '#fff';
        canvas_buffer.fillText(
          'Turn#' + turns + turn_limit_string + ' ' + players[player_ids[turn]]['name'],
          0,
          x
        );
        x += 25;
    }

    if(unclaimed > 0){
        // Draw unclaimed hexagons.
        canvas_buffer.fillStyle = core_storage_data['default-color'],
        canvas_buffer.fillText(
          'Unclaimed:' + unclaimed,
          0,
          x
        );
        x += 25;
    }

    // Draw scoreboard.
    for(var player in scoreboard){
        if(!players[scoreboard[player]['id']]){
            continue;
        }

        canvas_buffer.fillStyle = players[scoreboard[player]['id']]['color'];
        canvas_buffer.fillText(
          players[scoreboard[player]['id']]['name']
            + (players[scoreboard[player]['id']]['done']
              ? '='
              : ':')
            + scoreboard[player]['hexagons'],
          0,
          x
        );
        x += 25;
    }

    // Draw winner.
    if(game_over){
        canvas_buffer.fillStyle = players[scoreboard[0]['id']]['color'];
        canvas_buffer.fillText(
          players[scoreboard[0]['id']]['name'] + ' wins!',
          0,
          x
        );
    }
}

function end_turn(){
    var over = true;
    for(var player in players){
        if(!players[player]['done']){
            over = false;
            break;
        }
    }
    if(over
      || turns >= core_storage_data['turn-limit']){
        game_over = true;
        return;
    }

    if(turn >= player_ids.length - 1){
        turn = 0;

    }else{
        turn += 1;
    }

    if(!players[player_ids[turn]]){
        end_turn();

    }else{
        turns += 1;
    }
}

function handle_ai_turn(){
    if(!players[player_ids[turn]]
      || !players[player_ids[turn]]['ai']
      || game_over){
        return;
    }

    if(!players[player_ids[turn]]['done']){
        var options = [];
        var options_used = true;
        for(var hexagon in hexagons){
            if(hexagons[hexagon]['color'] === players[player_ids[turn]]['color']){
                continue;
            }

            if(check_neighbor_match({
              'x': hexagons[hexagon]['x'],
              'y': hexagons[hexagon]['y'],
            })){
                if(hexagons[hexagon]['color'] === core_storage_data['default-color']){
                    conquer_hexagon(hexagon);
                    options_used = false;
                    break;

                }else{
                    options.push(hexagon);
                }
            }
        }
        if(options_used){
            if(options.length > 0){
                sort_random({
                  'array': options,
                });
                scoreboard_loop:
                for(var i = scoreboard.length; i--;){
                    if(!players[scoreboard[i]['id']]){
                        continue;
                    }

                    for(var option in options){
                        if(hexagons[options[option]]['color'] === players[scoreboard[i]['id']]['color']){
                            conquer_hexagon(options[option]);
                            break scoreboard_loop;
                        }
                    }
                }

            }else{
                players[player_ids[turn]]['done'] = true;
            }
        }
    }

    end_turn();
}

function logic(){
    // Move camera left.
    if(core_keys[65]['state']
      && camera['x'] < width_half){
        camera['x'] += core_storage_data['scroll-speed'];
    }

    // Move camera right.
    if(core_keys[68]['state']
      && camera['x'] > -width_half){
        camera['x'] -= core_storage_data['scroll-speed'];
    }

    // Move camera down.
    if(core_keys[83]['state']
      && camera['y'] > -height_half){
        camera['y'] -= core_storage_data['scroll-speed'];
    }

    // Move camera up.
    if(core_keys[87]['state']
      && camera['y'] < height_half){
        camera['y'] += core_storage_data['scroll-speed'];
    }

    handle_ai_turn();
    update_scoreboard();
}

function lose_hexagon(player){
    players[player]['hexagons'] -= 1;
    if(players[player]['hexagons'] <= 0){
        delete players[player];
        player_count -= 1;
    }
}

function repo_init(){
    core_repo_init({
      'info': '<input onclick=canvas_setmode({mode:1,newgame:true}) type=button value="New Game">',
      'keybinds': {
        65: {},
        68: {},
        72: {
          'todo': function(){
              if(players[player_ids[turn]]
                && !players[player_ids[turn]]['ai']){
                  end_turn();
              }
          },
        },
        80: {
          'todo': function(){
              if(!game_over
                && players[player_ids[turn]]
                && !players[player_ids[turn]]['ai']){
                  for(var hexagon in hexagons){
                      if(!players[player_ids[turn]]){
                          break;
                        }
                      if(hexagons[hexagon]['color'] === players[player_ids[turn]]['color']){
                          hexagons[hexagon]['color'] = core_storage_data['default-color'];
                          lose_hexagon(player_ids[turn]);
                          unclaimed += 1;
                      }
                  }
                  for(var player in players){
                      players[player]['done'] = false;
                  }
                  end_turn();
              }
          },
        },
        83: {},
        87: {},
      },
      'menu': true,
      'mousebinds': {
        'mousedown': {
          'todo': function(event){
              if(canvas_mode <= 0
                || !players[player_ids[turn]]
                || players[player_ids[turn]]['ai']){
                  return;
              }

              var position = select_hexagon(
                core_mouse['x'],
                core_mouse['y']
              );

              // Check if a hexagon exists at this location
              //   with a different color.
              var target = false;
              for(var hexagon in hexagons){
                  if(hexagons[hexagon]['x'] === position['x']
                    && hexagons[hexagon]['y'] === position['y']
                    && hexagons[hexagon]['color'] !== players[player_ids[turn]]['color']){
                      target = hexagon;
                      break;
                  }
              }
              if(target === false){
                  return;
              }

              // Check if current player has a hexagon next to target hexagon.
              if(!check_neighbor_match({
                'x': hexagons[target]['x'],
                'y': hexagons[target]['y'],
              })){
                  return;
              }

              // Attempt to conquer the hexagon.
              conquer_hexagon(hexagon);

              end_turn();
          },
        },
        'mousemove': {
          'todo': function(){
              var x = core_mouse['x'] - canvas_x - camera['x'];
              var y = core_mouse['y'] - canvas_y - camera['y'];
              var position = select_hexagon(
                select_y_mod(
                  x,
                  y
                ),
                y
              );
              core_mouse['x'] = position['x'];
              core_mouse['y'] = position['y'];
          },
        },
      },
      'storage': {
        'ai': 4,
        'default-color': '#ffffff',
        'height': 500,
        'hexagon-size': 25,
        'hexagons': 150,
        'ms-per-frame': 1,
        'players': 1,
        'scroll-speed': 5,
        'turn-limit': Infinity,
        'width': 500,
      },
      'storage-menu': '<input id=ai>AI
<input id=default-color type=color>Default Color
<input id=height>Height
<input id=hexagons>Hexagons
<input id=hexagon-size>Hexagon Size
<input id=ms-per-frame>ms/Frame
<input id=players>Players
<input id=scroll-speed>Scroll Speed
<input id=turn-limit>Turn Limit
<input id=width>Width',
      'title': 'Hexagons-2D.htm',
    });
    canvas_init();
}

function select_hexagon(x, y){
    return {
      'x': Math.ceil((x - x_scaled_half) / x_scaled) * x_scaled,
      'y': Math.ceil((y - y_scaled_half) / y_scaled) * y_scaled,
    };
}

function select_y_mod(x, y, move){
    move = move || -(x_scaled_half);

    var y_mod = Math.abs(y % y_scaled_double);
    if(y_mod > y_scaled_half
      && y_mod < y_scaled * 1.5){
        x += move;
    }

    return x;
}

function update_scoreboard(){
    scoreboard = [];
    for(var player in players){
        scoreboard.push({
          'hexagons': players[player]['hexagons'],
          'id': player,
        });
    }
    sort_property({
      'array': scoreboard,
      'property': 'hexagons',
      'reverse': true,
    });
}

var camera = {};
var game_over = false;
var height_half = 0;
var hexagon_size = 0;
var hexagons = [];
var player_count = 0;
var player_ids = [];
var players = {};
var scoreboard = [];
var turn = 0;
var turn_limit_string = '';
var turns = 0;
var unclaimed = 0;
var width_half = 0;
var x_scaled = 0;
var x_scaled_half = 0;
var y_scaled = 0;
var y_scaled_double = 0;
var y_scaled_half = 0;
<|endoftext|>


<commit_before>var fs = require('fs')
var hh = require('http-https')
var ipSet = require('ip-set')
var once = require('once')
var split = require('split')
var url = require('url')
var zlib = require('zlib')

var blocklistRe = /^\s*[^#].*?\s*:\s*([a-f0-9.:]+?)\s*-\s*([a-f0-9.:]+?)\s*$/

module.exports = function loadIPSet (input, cb) {
  cb = once(cb)
  if (Array.isArray(input) || !input) {
    process.nextTick(function () {
      cb(null, new ipSet(input))
    })
  } else if (/^https?:\/\//.test(input)) {
    var p = url.parse(input)
    var opts = {
      hostname: p.hostname,
      port: p.port,
      path: p.path,
      headers: {
        'accept-encoding': 'gzip, deflate'
      }
    }
    hh.get(opts, function (res) {
      res.on('error', cb)
      var encoding = res.headers['content-encoding']
      if (encoding === 'gzip') {
        onStream(res.pipe(zlib.Gunzip()))
      } else if (encoding === 'deflate') {
        onStream(res.pipe(zlib.createInflate().on('error', cb)))
      } else
        onStream(res)
    }).on('error', cb)
  } else {
    var f = fs.createReadStream(input).on('error', cb)
    if (/.gz$/.test(input))
      f = f.pipe(zlib.Gunzip().on('error', cb))
    onStream(f)
  }

  function onStream (stream) {
    var blocklist = []
    stream
      .pipe(split())
      .on('data', function (line) {
        var match = blocklistRe.exec(line)
        if (match) blocklist.push({ start: match[1], end: match[2] })
      })
      .on('end', function () {
        cb(null, new ipSet(blocklist))
      })
  }
}
<commit_msg>handle gzip errors<commit_after>var fs = require('fs')
var hh = require('http-https')
var ipSet = require('ip-set')
var once = require('once')
var split = require('split')
var url = require('url')
var zlib = require('zlib')

var blocklistRe = /^\s*[^#].*?\s*:\s*([a-f0-9.:]+?)\s*-\s*([a-f0-9.:]+?)\s*$/

module.exports = function loadIPSet (input, cb) {
  cb = once(cb)
  if (Array.isArray(input) || !input) {
    process.nextTick(function () {
      cb(null, new ipSet(input))
    })
  } else if (/^https?:\/\//.test(input)) {
    var p = url.parse(input)
    var opts = {
      hostname: p.hostname,
      port: p.port,
      path: p.path,
      headers: {
        'accept-encoding': 'gzip, deflate'
      }
    }
    hh.get(opts, function (res) {
      res.on('error', cb)
      var encoding = res.headers['content-encoding']
      if (encoding === 'gzip') {
        onStream(res.pipe(zlib.Gunzip().on('error', cb)))
      } else if (encoding === 'deflate') {
        onStream(res.pipe(zlib.createInflate().on('error', cb)))
      } else
        onStream(res)
    }).on('error', cb)
  } else {
    var f = fs.createReadStream(input).on('error', cb)
    if (/.gz$/.test(input))
      f = f.pipe(zlib.Gunzip().on('error', cb))
    onStream(f)
  }

  function onStream (stream) {
    var blocklist = []
    stream
      .pipe(split())
      .on('data', function (line) {
        var match = blocklistRe.exec(line)
        if (match) blocklist.push({ start: match[1], end: match[2] })
      })
      .on('end', function () {
        cb(null, new ipSet(blocklist))
      })
  }
}
<|endoftext|>


<commit_before>// TODO:
// - Use the same DHT object for looking up multiple torrents
// - Persist the routing table for later bootstrapping
// - Use actual DHT data structure with "buckets" (follow spec)
// - Add the method that allows us to list ourselves in the DHT
// - https://github.com/czzarr/node-bitwise-xor

module.exports = DHT

var bncode = require('bncode')
var compact2string = require('compact2string')
var debug = require('debug')('bittorrent-dht')
var dgram = require('dgram')
var EventEmitter = require('events').EventEmitter
var hat = require('hat')
var inherits = require('inherits')
var portfinder = require('portfinder')

// Use random port above 1024
portfinder.basePort = Math.floor(Math.random() * 60000) + 1025

var MAX_NODES = 5000
var REQ_TIMEOUT = 2000
var MAX_REQUESTS = 3
var BOOTSTRAP_TIMEOUT = 5000
var BOOTSTRAP_NODES = [
  'dht.transmissionbt.com:6881',
  'router.bittorrent.com:6881',
  'router.utorrent.com:6881'
]
var MAX_QUERY_PER_SECOND = 200
var QUEUE_QUERY_INTERVAL = Math.floor(1000/MAX_QUERY_PER_SECOND)

function parseNodeInfo (compact) {
  try {
    var nodes = []
    for (var i = 0; i < compact.length; i += 26) {
      nodes.push(compact2string(compact.slice(i + 20, i + 26)))
    }
    return nodes
  } catch (err) {
    debug('Invalid node info ' + compact)
    return []
  }
}

function parsePeerInfo (list) {
  try {
    return list.map(compact2string)
  } catch (err) {
    debug('Invalid peer info ' + list)
    return []
  }
}

inherits(DHT, EventEmitter)

/**
 * Create a new DHT
 * @param {string|Buffer} infoHash
 */
function DHT (opts) {
  if (!(this instanceof DHT)) return new DHT(opts)
  EventEmitter.call(this)

  if (!opts) opts = {}
  if (!opts.nodeId) opts.nodeId = hat(160)

  this.nodeId = typeof opts.nodeId === 'string'
    ? new Buffer(opts.nodeId, 'hex')
    : opts.nodeId

  this.nodes = {}
  this.peers = {}
  this.reqs = {}
  this.queue = [].concat(BOOTSTRAP_NODES)

  this.port = 0
  this.requestId = 1
  this.pendingRequests = {}
  // Number of nodes we still need to find to satisfy the last call to findPeers
  this.missingPeers = 0

  this.pendingRequests[this.requestId] = 1

  this.socket = dgram.createSocket('udp4')
  this.socket.on('message', this._onData.bind(this))
  this.socket.on('listening', this._onListening.bind(this))
}

DHT.prototype.close = function () {
  this.listening = false
  this._closed = true
  this.socket.close()
}

// TODO: support setting multiple infohashes
DHT.prototype.setInfoHash = function (infoHash) {
  this.infoHash = typeof infoHash === 'string'
    ? new Buffer(infoHash, 'hex')
    : infoHash

  this.message = {
    t: this.requestId.toString(),
    y: 'q',
    q: 'get_peers',
    a: {
      id: this.nodeId,
      info_hash: this.infoHash
    }
  }
  // console.log('Created DHT message: ' + JSON.stringify(this.message))
  this.message = bncode.encode(this.message)
}

DHT.prototype.query = function (addr) {
  var numNodes = Object.keys(this.nodes).length
  if (numNodes > MAX_NODES || this.missingPeers <= 0 || this._closed) return

  var host = addr.split(':')[0]
  var port = Number(addr.split(':')[1])
  if (!(port > 0 && port < 65535)) return
  this.socket.send(this.message, 0, this.message.length, port, host, function () {
    setTimeout(function () {
      this.reqs[addr] = (this.reqs[addr] || 0) + 1
      if (!this.nodes[addr] && this.reqs[addr] < MAX_REQUESTS) {
        this.query.call(this, addr)
      }
    }.bind(this), REQ_TIMEOUT)
  }.bind(this))
}

DHT.prototype._queryQueue = function() {
  if (this.queue.length) {
    this.query(this.queue.pop())
  } else {
    clearInterval(this.queueInterval);
    this.queueInterval = null;
  }
}

/* Start querying queue, if not already */
DHT.prototype.queryQueue = function() {
  if (!this.queryInterval) {
    this.queryInterval = setInterval(this._queryQueue.bind(this), QUEUE_QUERY_INTERVAL);
  }
}

DHT.prototype.findPeers = function (num) {
  if (!num) num = 1

  // TODO: keep track of missing nodes for each `findPeers` call separately!
  this.missingPeers += num

  // Start querying queue
  this.queryQueue()

  // If we are connected to no nodes after timeout period, then retry with
  // the bootstrap nodes.
  setTimeout(function () {
    if (Object.keys(this.nodes).length === 0) {
      debug('No DHT nodes replied, retry with bootstrap nodes')
      this.queue.push.apply(this.queue, BOOTSTRAP_NODES)
      this.queryQueue()
    }
  }.bind(this), BOOTSTRAP_TIMEOUT)
}

DHT.prototype.listen = function (port, onlistening) {
  if (typeof port === 'function') {
    onlistening = port
    port = undefined
  }

  if (onlistening)
    this.once('listening', onlistening)

  var onPort = function (err, port) {
    if (err)
      return this.emit('error', err)
    this.port = port
  }.bind(this)

  if (port)
    onPort(null, port)
  else
    portfinder.getPort(onPort)

  this.socket.bind(port)
}

DHT.prototype._onListening = function () {
  this.listening = true
  this.emit('listening', this.port)
}

/**
 * Called when client finds a new DHT node
 * @param  {string} addr
 */
DHT.prototype._handleNode = function (addr) {
  if (this.nodes[addr]) {
    // console.log('already know about this node!')
    return
  }

  //if (this.queue.length < 10000) this.queue.push(addr) // TODO: Something like this might be needed for safety. (?)
  this.queue.push(addr)
  this.queryQueue()

  this.emit('node', addr, this.infoHash.toString('hex'))
}

/**
 * Called when client finds a new peer
 * @param  {string} addr
 */
DHT.prototype._handlePeer = function (addr) {
  if (this.peers[addr]) return
  this.peers[addr] = true
  this.missingPeers = Math.max(0, this.missingPeers - 1)

  this.emit('peer', addr, this.infoHash.toString('hex'))
}

DHT.prototype._onData = function (data, rinfo) {
  var addr = rinfo.address + ':' + rinfo.port

  var message
  try {
    // console.log('got response from ' + addr)
    message = bncode.decode(data)
    if (!message) throw new Error('message is undefined')
  } catch (err) {
    debug('Failed to decode data from node ' + addr + ' ' + err.message)
    return
  }

  if (!message.t || (message.t.toString() !== this.requestId.toString())) {
    // console.log('DHT received wrong message requestId: ', message.t && message.t.toString(), this.requestId && this.requestId.toString(), addr)
    return
  }

  // Mark that we've seen this node (the one we received data from)
  this.nodes[addr] = true
  delete this.reqs[addr]

  var r = message && message.r

  if (r && Buffer.isBuffer(r.nodes)) {
    // console.log('got nodes')
    parseNodeInfo(r.nodes).forEach(this._handleNode.bind(this))
  }
  if (r && Array.isArray(r.values)) {
    // console.log('got peers')
    parsePeerInfo(r.values).forEach(this._handlePeer.bind(this))
  }
}
<commit_msg>fix PR regression: retry bootstrap nodes multiple times<commit_after>// TODO:
// - Use the same DHT object for looking up multiple torrents
// - Persist the routing table for later bootstrapping
// - Use actual DHT data structure with "buckets" (follow spec)
// - Add the method that allows us to list ourselves in the DHT
// - https://github.com/czzarr/node-bitwise-xor

module.exports = DHT

var bncode = require('bncode')
var compact2string = require('compact2string')
var debug = require('debug')('bittorrent-dht')
var dgram = require('dgram')
var EventEmitter = require('events').EventEmitter
var hat = require('hat')
var inherits = require('inherits')
var portfinder = require('portfinder')

// Use random port above 1024
portfinder.basePort = Math.floor(Math.random() * 60000) + 1025

var MAX_NODES = 5000
var REQ_TIMEOUT = 2000
var MAX_REQUESTS = 3
var BOOTSTRAP_TIMEOUT = 5000
var BOOTSTRAP_NODES = [
  'dht.transmissionbt.com:6881',
  'router.bittorrent.com:6881',
  'router.utorrent.com:6881'
]
var MAX_QUERY_PER_SECOND = 200
var QUEUE_QUERY_INTERVAL = Math.floor(1000/MAX_QUERY_PER_SECOND)

function parseNodeInfo (compact) {
  try {
    var nodes = []
    for (var i = 0; i < compact.length; i += 26) {
      nodes.push(compact2string(compact.slice(i + 20, i + 26)))
    }
    return nodes
  } catch (err) {
    debug('Invalid node info ' + compact)
    return []
  }
}

function parsePeerInfo (list) {
  try {
    return list.map(compact2string)
  } catch (err) {
    debug('Invalid peer info ' + list)
    return []
  }
}

inherits(DHT, EventEmitter)

/**
 * Create a new DHT
 * @param {string|Buffer} infoHash
 */
function DHT (opts) {
  if (!(this instanceof DHT)) return new DHT(opts)
  EventEmitter.call(this)

  if (!opts) opts = {}
  if (!opts.nodeId) opts.nodeId = hat(160)

  this.nodeId = typeof opts.nodeId === 'string'
    ? new Buffer(opts.nodeId, 'hex')
    : opts.nodeId

  this.nodes = {}
  this.peers = {}
  this.reqs = {}
  this.queue = [].concat(BOOTSTRAP_NODES)

  this.port = 0
  this.requestId = 1
  this.pendingRequests = {}
  // Number of nodes we still need to find to satisfy the last call to findPeers
  this.missingPeers = 0

  this.pendingRequests[this.requestId] = 1

  this.socket = dgram.createSocket('udp4')
  this.socket.on('message', this._onData.bind(this))
  this.socket.on('listening', this._onListening.bind(this))
}

DHT.prototype.close = function () {
  this.listening = false
  this._closed = true
  this.socket.close()
}

// TODO: support setting multiple infohashes
DHT.prototype.setInfoHash = function (infoHash) {
  this.infoHash = typeof infoHash === 'string'
    ? new Buffer(infoHash, 'hex')
    : infoHash

  this.message = {
    t: this.requestId.toString(),
    y: 'q',
    q: 'get_peers',
    a: {
      id: this.nodeId,
      info_hash: this.infoHash
    }
  }
  // console.log('Created DHT message: ' + JSON.stringify(this.message))
  this.message = bncode.encode(this.message)
}

DHT.prototype.query = function (addr) {
  var numNodes = Object.keys(this.nodes).length
  if (numNodes > MAX_NODES || this.missingPeers <= 0 || this._closed) return

  var host = addr.split(':')[0]
  var port = Number(addr.split(':')[1])
  if (!(port > 0 && port < 65535)) return
  this.socket.send(this.message, 0, this.message.length, port, host, function () {
    setTimeout(function () {
      this.reqs[addr] = (this.reqs[addr] || 0) + 1
      if (!this.nodes[addr] && this.reqs[addr] < MAX_REQUESTS) {
        this.query.call(this, addr)
      }
    }.bind(this), REQ_TIMEOUT)
  }.bind(this))
}

DHT.prototype._queryQueue = function() {
  if (this.queue.length) {
    this.query(this.queue.pop())
  } else {
    clearInterval(this.queueInterval);
    this.queueInterval = null;
  }
}

/* Start querying queue, if not already */
DHT.prototype.queryQueue = function() {
  if (!this.queryInterval) {
    this.queryInterval = setInterval(this._queryQueue.bind(this), QUEUE_QUERY_INTERVAL);
  }
}

DHT.prototype.findPeers = function (num) {
  if (!num) num = 1

  // TODO: keep track of missing nodes for each `findPeers` call separately!
  this.missingPeers += num

  // Start querying queue
  this.queryQueue()

  // If we are connected to no nodes after timeout period, then retry with
  // the bootstrap nodes.
  setTimeout(function () {
    if (Object.keys(this.nodes).length === 0) {
      debug('No DHT nodes replied, retry with bootstrap nodes')
      this.queue.push.apply(this.queue, BOOTSTRAP_NODES)
      this.missingPeers = 0
      this.findPeers(num)
    }
  }.bind(this), BOOTSTRAP_TIMEOUT)
}

DHT.prototype.listen = function (port, onlistening) {
  if (typeof port === 'function') {
    onlistening = port
    port = undefined
  }

  if (onlistening)
    this.once('listening', onlistening)

  var onPort = function (err, port) {
    if (err)
      return this.emit('error', err)
    this.port = port
  }.bind(this)

  if (port)
    onPort(null, port)
  else
    portfinder.getPort(onPort)

  this.socket.bind(port)
}

DHT.prototype._onListening = function () {
  this.listening = true
  this.emit('listening', this.port)
}

/**
 * Called when client finds a new DHT node
 * @param  {string} addr
 */
DHT.prototype._handleNode = function (addr) {
  if (this.nodes[addr]) {
    // console.log('already know about this node!')
    return
  }

  //if (this.queue.length < 10000) this.queue.push(addr) // TODO: Something like this might be needed for safety. (?)
  this.queue.push(addr)
  this.queryQueue()

  this.emit('node', addr, this.infoHash.toString('hex'))
}

/**
 * Called when client finds a new peer
 * @param  {string} addr
 */
DHT.prototype._handlePeer = function (addr) {
  if (this.peers[addr]) return
  this.peers[addr] = true
  this.missingPeers = Math.max(0, this.missingPeers - 1)

  this.emit('peer', addr, this.infoHash.toString('hex'))
}

DHT.prototype._onData = function (data, rinfo) {
  var addr = rinfo.address + ':' + rinfo.port

  var message
  try {
    // console.log('got response from ' + addr)
    message = bncode.decode(data)
    if (!message) throw new Error('message is undefined')
  } catch (err) {
    debug('Failed to decode data from node ' + addr + ' ' + err.message)
    return
  }

  if (!message.t || (message.t.toString() !== this.requestId.toString())) {
    // console.log('DHT received wrong message requestId: ', message.t && message.t.toString(), this.requestId && this.requestId.toString(), addr)
    return
  }

  // Mark that we've seen this node (the one we received data from)
  this.nodes[addr] = true
  delete this.reqs[addr]

  var r = message && message.r

  if (r && Buffer.isBuffer(r.nodes)) {
    // console.log('got nodes')
    parseNodeInfo(r.nodes).forEach(this._handleNode.bind(this))
  }
  if (r && Array.isArray(r.values)) {
    // console.log('got peers')
    parsePeerInfo(r.values).forEach(this._handlePeer.bind(this))
  }
}
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var $ = require('jquery'); $.noConflict();

exports = module.exports = SelectorObserver;

/**
 * @param {Object} conf
 * @param {String} conf.observeList
 */
function SelectorObserver(conf) {
    assert('MutationObserver' in window, 'MutationObserver not supported');

    assert(typeof conf === 'object', 'conf is not an object');
    assert(__isArray(conf.observeList), 'conf.observeList is not an array');
    // TODO observeList.selector's must be unique

    this._conf = conf;

    this._selectorPrevVisible = this._conf.observeList.map(function () {
        return null;
    });

    // first run: determine starting states of observed selectors
    this._onMutation();

    this._mutationObserver = new window.MutationObserver(this._onMutation.bind(this));
    this._mutationObserver.observe(document.body, { childList: true, subtree: true, attributeFilter: ['style', 'class'] });
}

SelectorObserver.prototype._onMutation = function () {
    var self = this;

    self._conf.observeList.forEach(function (item, i) {
        var prevIsVisible = self._selectorPrevVisible[i];
        var isVisible = $(item.selector).is(':visible');

        // console.log('[SelectorObserver] '+item.selector+(isVisible?' visible':' not visible'))

        try {
            if (prevIsVisible !== null && !prevIsVisible && isVisible) {
                item.listener();
            }
        }
        catch (error) {
            console.error(error);
        }

        self._selectorPrevVisible[i] = isVisible;
    });
};

SelectorObserver.prototype.disconnect = function () {
    this._mutationObserver.disconnect();
};

function __isArray(val) {
    return Object.prototype.toString.call(val) === '[object Array]';
}
<commit_msg>Fix mutationObserver in Edge<commit_after>'use strict';

var assert = require('assert');
var $ = require('jquery'); $.noConflict();

exports = module.exports = SelectorObserver;

/**
 * @param {Object} conf
 * @param {String} conf.observeList
 */
function SelectorObserver(conf) {
    assert('MutationObserver' in window, 'MutationObserver not supported');

    assert(typeof conf === 'object', 'conf is not an object');
    assert(__isArray(conf.observeList), 'conf.observeList is not an array');
    // TODO observeList.selector's must be unique

    this._conf = conf;

    this._selectorPrevVisible = this._conf.observeList.map(function () {
        return null;
    });

    // first run: determine starting states of observed selectors
    this._onMutation();

    this._mutationObserver = new window.MutationObserver(this._onMutation.bind(this));
    this._mutationObserver.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
}

SelectorObserver.prototype._onMutation = function () {
    var self = this;

    self._conf.observeList.forEach(function (item, i) {
        var prevIsVisible = self._selectorPrevVisible[i];
        var isVisible = $(item.selector).is(':visible');

        // console.log('[SelectorObserver] '+item.selector+(isVisible?' visible':' not visible'))

        try {
            if (prevIsVisible !== null && !prevIsVisible && isVisible) {
                item.listener();
            }
        }
        catch (error) {
            console.error(error);
        }

        self._selectorPrevVisible[i] = isVisible;
    });
};

SelectorObserver.prototype.disconnect = function () {
    this._mutationObserver.disconnect();
};

function __isArray(val) {
    return Object.prototype.toString.call(val) === '[object Array]';
}
<|endoftext|>


<commit_before>//iTop Designer combo box for icons
$(function()
{
	// the widget definition, where "itop" is the namespace,
	// "icon_select" the widget name
	$.widget( "itop.icon_select",
	{
		// default options
		options:
		{
			items: [],
			current_idx: 0,
			labels: {cancel: 'Cancel', pick_icon_file: 'Select an icon file to upload:', upload_dlg_title: 'Icon Upload...', upload: 'Upload...'},
			post_upload_to: null
		},

		// the constructor
		_create: function()
		{
			var me = this;
			var sLabel = '';
			var sIcon = '';
			for(var i in this.options.items)
			{
				if(this.options.items[i].icon == '')
				{
					this.options.items[i].icon = GetAbsoluteUrlAppRoot()+'images/transparent_32_32.png';
				}
			}
			if (this.options.items.length > 0)
			{
				sIcon = this.options.items[this.options.current_idx].icon;
				sLabel = this.options.items[this.options.current_idx].label;
			}
			this.oImg = $('');
			this.oLabel = $(''+sLabel+'');
			this.oButton = $('<button type="button">

</button>');
			this.oButton.prepend(this.oLabel).prepend(this.oImg);
			this.oButton.click(function(event, ui) { me._on_button_clicked(event, ui); });
			this.element.after(this.oButton);
			this.element.addClass( "itop-icon-select" ).button();
			this.element.bind( "reverted.itop-icon-select", function(ev, data) {
				var idx = me._find_item(data.previous_value);
				if (idx != null)
				{
					me.oImg.attr('src', me.options.items[idx].icon);
					me.oLabel.text(me.options.items[idx].label);
				}
			});
			if (this.options.post_upload_to != null)
			{
				this.oUploadBtn = $('<button type="button" title="'+this.options.labels['upload']+'">

</button>');
				this.oUploadBtn.click( function() { me._upload_dlg(); } );
				this.oButton.after(this.oUploadBtn);
			}
			var id = this.element.attr('id');
			$('#event_bus').bind('tabshow.itop-icon-select'+id, function(event) {
				// Compute the offsetX the first time the 'element' becomes visible...
				var bVisible = me.element.parent().is(':visible');
				if ((me.options.offsetX == null) && (bVisible))
				{
					me._refresh();
				}
			});
			this.oUploadDlg = null;
			this._refresh();
		},

		// called when created, and later when changing options
		_refresh: function()
		{
			if (!this.element.parent().is(':visible'))
			{
				this.options.offsetX = null; // Menu needs to be reconstructed when the button becomes visible
			}
			else
			{
				if (this.options.items.length > 0)
				{
					this.element.val(this.options.items[this.options.current_idx].value);
					this.oImg.attr('src', this.options.items[this.options.current_idx].icon);
					this.oLabel.text(this.options.items[this.options.current_idx].label);
				}
				this._create_menu();
			}
		},
		_create_menu: function()
		{
			var me = this;
			var sMenu = '
';
			for(var i in this.options.items)
			{
				sMenu = sMenu + '
'+this.options.items[i].label+'
';
			}
			sMenu = sMenu + '
';
			var iWidth = Math.max(250, this.oButton.width());
			this.oMenu = this.oButton.menu({ content: sMenu, callback: function(data) {me._on_icon_selection(data);}, showSpeed: 0, maxHeight: 300, flyOut: true, width: iWidth, positionOpts: {posX: 'left', posY: 'top', offsetX: 0, offsetY: 0} });
		},
		_on_button_clicked: function(event, ui)
		{
			// Adjust the position of the menu, in case the button was moved...
			// The simpler is to kill and rebuild the menu !!!
			KillAllMenus();
			this._create_menu();
		},

		// events bound via _bind are removed automatically
		// revert other modifications here
		_destroy: function()
		{
			this.element.removeClass( "itop-icon-select" );
			this.oButton.button( "destroy" );
		},

		// _setOptions is called with a hash of all options that are changing
		// always refresh when changing options
		_setOptions: function()
		{
			// in 1.9 would use _superApply
			this._superApply(arguments);
			this._refresh();
		},

		// _setOption is called for each individual option that is changing
		_setOption: function( key, value )
		{
			if (key == 'current_idx')
			{
				this.element.val(this.options.items[value].value).trigger('change');
			}

			// in 1.9 would use _super
			this._superApply(arguments);
		},
		_on_icon_selection: function(data)
		{
			this._setOptions({current_idx: data.item.attr('value')});
		},
		_find_item: function(value)
		{
			var res = null;
			for(var idx in this.options.items)
			{
				if (value == this.options.items[idx].value)
				{
					res = idx;
					break;
				}
			}
			return res;
		},
		add_item: function(value, label, icon, position)
		{
			if (position == 'bottom')
			{
				this.options.items.push({value: value, label: label, icon: icon });
			}
			else
			{
				// Assume 'top'
				this.options.items.unshift({value: value, label: label, icon: icon });
			}
			this._refresh();
		},
		get_post_upload_to: function()
		{
			return this.options.post_upload_to;
		},
		_upload_dlg: function()
		{
			var me = this;
			this.oUploadDlg = $('

'+this.options.labels['pick_icon_file']+'

<input type="file" name="file" id="file"/>

');
			this.element.after(this.oUploadDlg);
			$('input[type=file]').bind('change', function() { me._do_upload(); });
			this.oUploadDlg.dialog({
				width: 400,
				modal: true,
				title: this.options.labels['upload_dlg_title'],
				buttons: [
				{ text: this.options.labels['cancel'], click: function() {
					me.oUploadDlg.dialog( "close" );
					}
				}
				],
				close: function() { me._on_upload_close(); }
			});
		},
		_on_upload_close: function()
		{
			this.oUploadDlg.remove();
			this.oUploadDlg = null;
		},
		_do_upload: function()
		{
			var me = this;
			$.ajaxFileUpload
			(
				{
					url: this.options.post_upload_to,
					secureuri:false,
					fileElementId:'file',
					dataType: 'json',
					success: function (data, status)
					{
						me._on_upload_complete(data);
					},
					error: function (data, status, e)
					{
						me._on_upload_error(data, status, e);
					}
				}
			);
		},
		_on_upload_complete: function(data)
		{
			//console.log(data);
			//console.log(data.icon);
			var sIcon = data.icon.replace(/&/g, "&");
			//console.log(sIcon);
			this.add_item(data.id, data.msg, sIcon, 'top');
			this.element.val(data.id);
			var idx = this._find_item(data.id);
			if (idx != null)
			{
				this.oImg.attr('src', this.options.items[idx].icon);
				this.oLabel.text(this.options.items[idx].label);
			}
			this.element.trigger('change');
			this.oUploadDlg.dialog( "close" );
		},
		_on_upload_error: function(data, status, e)
		{
			alert(e);
		}
	});
});
<commit_msg>Support for some (optional) feedback during uploads.<commit_after>//iTop Designer combo box for icons
$(function()
{
	// the widget definition, where "itop" is the namespace,
	// "icon_select" the widget name
	$.widget( "itop.icon_select",
	{
		// default options
		options:
		{
			items: [],
			current_idx: 0,
			labels: {cancel: 'Cancel', pick_icon_file: 'Select an icon file to upload:', upload_dlg_title: 'Icon Upload...', upload: 'Upload...'},
			post_upload_to: null
		},

		// the constructor
		_create: function()
		{
			var me = this;
			var sLabel = '';
			var sIcon = '';
			for(var i in this.options.items)
			{
				if(this.options.items[i].icon == '')
				{
					this.options.items[i].icon = GetAbsoluteUrlAppRoot()+'images/transparent_32_32.png';
				}
			}
			if (this.options.items.length > 0)
			{
				sIcon = this.options.items[this.options.current_idx].icon;
				sLabel = this.options.items[this.options.current_idx].label;
			}
			this.oImg = $('');
			this.oLabel = $(''+sLabel+'');
			this.oButton = $('<button type="button" class="icon-select">

</button>');
			this.oButton.prepend(this.oLabel).prepend(this.oImg);
			this.oButton.click(function(event, ui) { me._on_button_clicked(event, ui); });
			this.element.after(this.oButton);
			this.element.addClass( "itop-icon-select" ).button();
			this.element.bind( "reverted.itop-icon-select", function(ev, data) {
				var idx = me._find_item(data.previous_value);
				if (idx != null)
				{
					me.oImg.attr('src', me.options.items[idx].icon);
					me.oLabel.text(me.options.items[idx].label);
				}
			});
			if (this.options.post_upload_to != null)
			{
				this.oUploadBtn = $('<button class="icon-select" type="button" title="'+this.options.labels['upload']+'">

</button>');
				this.oUploadBtn.click( function() { me._upload_dlg(); } );
				this.oButton.after(this.oUploadBtn);
			}
			var id = this.element.attr('id');
			$('#event_bus').bind('tabshow.itop-icon-select'+id, function(event) {
				// Compute the offsetX the first time the 'element' becomes visible...
				var bVisible = me.element.parent().is(':visible');
				if ((me.options.offsetX == null) && (bVisible))
				{
					me._refresh();
				}
			});
			this.oUploadDlg = null;
			this._refresh();
		},

		// called when created, and later when changing options
		_refresh: function()
		{
			if (!this.element.parent().is(':visible'))
			{
				this.options.offsetX = null; // Menu needs to be reconstructed when the button becomes visible
			}
			else
			{
				if (this.options.items.length > 0)
				{
					this.element.val(this.options.items[this.options.current_idx].value);
					this.oImg.attr('src', this.options.items[this.options.current_idx].icon);
					this.oLabel.text(this.options.items[this.options.current_idx].label);
				}
				this._create_menu();
			}
		},
		_create_menu: function()
		{
			var me = this;
			var sMenu = '
';
			for(var i in this.options.items)
			{
				sMenu = sMenu + '
'+this.options.items[i].label+'
';
			}
			sMenu = sMenu + '
';
			var iWidth = Math.max(250, this.oButton.width());
			this.oMenu = this.oButton.menu({ content: sMenu, callback: function(data) {me._on_icon_selection(data);}, showSpeed: 0, maxHeight: 300, flyOut: true, width: iWidth, positionOpts: {posX: 'left', posY: 'top', offsetX: 0, offsetY: 0} });
		},
		_on_button_clicked: function(event, ui)
		{
			// Adjust the position of the menu, in case the button was moved...
			// The simpler is to kill and rebuild the menu !!!
			KillAllMenus();
			this._create_menu();
		},

		// events bound via _bind are removed automatically
		// revert other modifications here
		_destroy: function()
		{
			this.element.removeClass( "itop-icon-select" );
			this.oButton.button( "destroy" );
		},

		// _setOptions is called with a hash of all options that are changing
		// always refresh when changing options
		_setOptions: function()
		{
			// in 1.9 would use _superApply
			this._superApply(arguments);
			this._refresh();
		},

		// _setOption is called for each individual option that is changing
		_setOption: function( key, value )
		{
			if (key == 'current_idx')
			{
				this.element.val(this.options.items[value].value).trigger('change');
			}

			// in 1.9 would use _super
			this._superApply(arguments);
		},
		_on_icon_selection: function(data)
		{
			this._setOptions({current_idx: data.item.attr('value')});
		},
		_find_item: function(value)
		{
			var res = null;
			for(var idx in this.options.items)
			{
				if (value == this.options.items[idx].value)
				{
					res = idx;
					break;
				}
			}
			return res;
		},
		add_item: function(value, label, icon, position)
		{
			if (position == 'bottom')
			{
				this.options.items.push({value: value, label: label, icon: icon });
			}
			else
			{
				// Assume 'top'
				this.options.items.unshift({value: value, label: label, icon: icon });
			}
			this._refresh();
		},
		get_post_upload_to: function()
		{
			return this.options.post_upload_to;
		},
		_upload_dlg: function()
		{
			var me = this;
			this.oUploadDlg = $('

'+this.options.labels['pick_icon_file']+'

<input type="file" name="file" id="file"/>

');
			this.element.after(this.oUploadDlg);
			$('input[type=file]').bind('change', function() { me._do_upload(); });
			this.oUploadDlg.dialog({
				width: 400,
				modal: true,
				title: this.options.labels['upload_dlg_title'],
				buttons: [
				{ text: this.options.labels['cancel'], click: function() {
					me.oUploadDlg.dialog( "close" );
					}
				}
				],
				close: function() { me._on_upload_close(); }
			});
		},
		_on_upload_close: function()
		{
			this.oUploadDlg.remove();
			this.oUploadDlg = null;
		},
		_do_upload: function()
		{
			var me = this;
			var $element = this.oUploadDlg.find('#file');
			this.oUploadDlg.closest('.ui-dialog').find('.ui-button').button('disable');
			if (ReplaceWithAnimation)
			{
				ReplaceWithAnimation($element);
			}
			$.ajaxFileUpload
			(
				{
					url: this.options.post_upload_to,
					secureuri:false,
					fileElementId:'file',
					dataType: 'json',
					success: function (data, status)
					{
						me._on_upload_complete(data);
					},
					error: function (data, status, e)
					{
						me._on_upload_error(data, status, e);
					}
				}
			);
		},
		_on_upload_complete: function(data)
		{
			//console.log(data);
			//console.log(data.icon);
			var sIcon = data.icon.replace(/&/g, "&");
			//console.log(sIcon);
			this.add_item(data.id, data.msg, sIcon, 'top');
			this.element.val(data.id);
			var idx = this._find_item(data.id);
			if (idx != null)
			{
				this.oImg.attr('src', this.options.items[idx].icon);
				this.oLabel.text(this.options.items[idx].label);
			}
			this.element.trigger('change');
			this.oUploadDlg.dialog('close');
		},
		_on_upload_error: function(data, status, e)
		{
			alert(e);
			this.oUploadDlg.closest('.ui-dialog').find('.ui-button').button('enable');
		}
	});
});
<|endoftext|>


<commit_before>var firebase = require('firebase');
firebase.initializeApp({
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_DATABASE_URL,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID
});

var Botkit = require('botkit');
var controller = Botkit.slackbot();
controller.configureSlackApp({
  clientId: process.env.SLACK_CLIENT_ID,
  clientSecret: process.env.SLACK_CLIENT_SECRET,
  redirectUri: 'http://localhost:3000/slack/callback',
  scopes: ['commands']
});

var request = require('request');
var express = require('express');
var app = express()
app.listen(process.env.PORT || 3000, function () {});

// TODO: Handle the res.send for success and failure
app.get('/slack/callback', function(req, res) {
  var url = 'https://slack.com/api/oauth.access?';
  url += 'client_id=' + process.env.SLACK_CLIENT_ID;
  url += '&client_secret=' + process.env.SLACK_CLIENT_SECRET;
  url += '&code=' + req.query.code;

  request(url, function (error, response, body) {
    if (error || response.statusCode != 200) {
      console.log('Request Error: ' + error)
    } else {
      var data = JSON.parse(body)
      if (!data.ok) {
        console.log('Slack OAuth Error: ' + data.error)
      } else {
        var team = {}
        team[data.team_id] = {
          access_token: data.access_token,
          scope: data.scope,
          user_id: data.user_id,
          team_id: data.team_id,
          team_name: data.team_name
        }

        firebase.database().ref('/slack/').update(team, function(error) {
          if (error) {
            console.log('Firebase Error: ' + error)
          } else {
            console.log(team[data.team_id].team_name + ' was added to Firebase')
            res.send('Hello World!');
          }
        });
      }
    }
  });
});

app.get('/slack/firesong', function(req, res) {
  console.log(req)
  console.log('gettt')
  // res.send('Hello World firesong get!');
});
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/slack/firesong', function(req, res) {
  console.log(req)
  console.log('posttt')
  res.send({
    "response_type": "in_channel",
    "text": "This is some response text."
  });
});

app.get('/slack/firesong-add', function(req, res) {
  console.log(req)
  res.send('Hello World firesong-add!');
});
<commit_msg>post 4<commit_after>var firebase = require('firebase');
firebase.initializeApp({
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_DATABASE_URL,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID
});

var Botkit = require('botkit');
var controller = Botkit.slackbot();
controller.configureSlackApp({
  clientId: process.env.SLACK_CLIENT_ID,
  clientSecret: process.env.SLACK_CLIENT_SECRET,
  redirectUri: 'http://localhost:3000/slack/callback',
  scopes: ['commands']
});

var request = require('request');
var url = require('url');
var express = require('express');
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(process.env.PORT || 3000, function () {});

// TODO: Handle the res.send for success and failure
app.get('/slack/callback', function(req, res) {
  var url = 'https://slack.com/api/oauth.access?';
  url += 'client_id=' + process.env.SLACK_CLIENT_ID;
  url += '&client_secret=' + process.env.SLACK_CLIENT_SECRET;
  url += '&code=' + req.query.code;

  request(url, function (error, response, body) {
    if (error || response.statusCode != 200) {
      console.log('Request Error: ' + error)
    } else {
      var data = JSON.parse(body)
      if (!data.ok) {
        console.log('Slack OAuth Error: ' + data.error)
      } else {
        var team = {}
        team[data.team_id] = {
          access_token: data.access_token,
          scope: data.scope,
          user_id: data.user_id,
          team_id: data.team_id,
          team_name: data.team_name
        }

        firebase.database().ref('/slack/').update(team, function(error) {
          if (error) {
            console.log('Firebase Error: ' + error)
          } else {
            console.log(team[data.team_id].team_name + ' was added to Firebase')
            res.send('Hello World!');
          }
        });
      }
    }
  });
});

app.get('/slack/firesong', function(req, res) {
  console.log(req)
  console.log('gettt')
  // res.send('Hello World firesong get!');
});

app.post('/slack/firesong', function(req, res) {
  console.log('body ' + req.body)
  console.log('posttt')
  res.send({
    "response_type": "in_channel",
    "text": "This is some response text."
  });
});

app.get('/slack/firesong-add', function(req, res) {
  console.log(req)
  res.send('Hello World firesong-add!');
});
<|endoftext|>


<commit_before>'use strict';

define(['app', 'Forwarders'], function(app, Forwarders) {
    app.controller('ForwarderAdd', [
        '$scope',
        '$state',
        'ForwardersFactory',
        function($scope, $state, ForwardersFactory) {

            $scope.forwarder = {};
            $scope.submit = function(form) {
                ForwardersFactory.save($scope.forwarder, function(err) {
                    if (err.errors) {
                        for (var key in err.errors) {
                            form[key].message = err.errors[key].message;
                        }
                    }else{
                        $state.go('/settings_forwarder');
                    }
                });
            };
            $scope.clear = function() {
                $scope.forwarder = angular.copy({});
            };
        }
    ]);

});
<commit_msg>fixed typo<commit_after>'use strict';

define(['app', 'Forwarders'], function(app, Forwarders) {
    app.controller('ForwarderAdd', [
        '$scope',
        '$state',
        'ForwardersFactory',
        function($scope, $state, ForwardersFactory) {

            $scope.forwarder = {};
            $scope.submit = function(form) {
                ForwardersFactory.save($scope.forwarder, function(err) {
                    if (err.errors) {
                        for (var key in err.errors) {
                            form[key].message = err.errors[key].message;
                        }
                    }else{
                        $state.go('settings_forwarder');
                    }
                });
            };
            $scope.clear = function() {
                $scope.forwarder = angular.copy({});
            };
        }
    ]);

});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { View, TouchableOpacity, BackAndroid } from 'react-native'
import { sendStoprequest } from '../actions/sendStoprequest'
import { Actions } from 'react-native-router-flux'

import { TitleBar, BoldTitleBar } from '../components/TitleBar'
import RouteInfo from '../components/RouteInfo'
import SlideConfirmButton from '../components/SlideConfirmButton'
import AccessibilityView from '../components/AccessibilityView'
import {DefaultText} from '../components/textComponents'

import styles from '../styles/stylesheet'
import strings from '../resources/translations'

import { fetchRouteStops } from '../actions/fetchRouteStops'

const UPDATE_INTERVAL_IN_SECS = 10

class StopRequestPage extends Component{
    constructor()
    {
        super()

        this.state = {
            renderConfirm: true,
            minutesLeft: this.props.vehicle.arrival + ' ' + strings.minutes,
            fetchIntervalRunning: false
        }

        this.sceneName = 'stopRequest'
    }

    createInterval = (props) =>
    {
        this.fetchInterval = setInterval(() =>
        {
            if (!props.isFetchingStops)
            {
                props.fetchRouteStops(this.props.vehicle.trip_id, this.props.stop.stopId, true)
            }
        }, UPDATE_INTERVAL_IN_SECS * 1000)
    }

    componentWillMount = () =>
    {
        this.props.fetchRouteStops(this.props.vehicle.trip_id, this.props.stop.stopId, true)
        this.setState({fetchIntervalRunning: true})
        this.createInterval(this.props)
    }

    componentWillReceiveProps = (nextProps) =>
      {
        this.setState({renderConfirm: !nextProps.sent})
        BackAndroid.addEventListener('hardwareBackPress', this.backAndroidHandler)

        if (nextProps.scene.name == this.sceneName)
        {
            if (!this.state.fetchIntervalRunning)
            {
                this.setState({fetchIntervalRunning: true})
                this.createInterval(nextProps)
            }
            if (typeof nextProps.routeStops[0] !== 'undefined' && nextProps.routeStops.length == 1)
            {
                if (nextProps.routeStops[0].arrives_in < 0)
                {
                    this.setState({minutesLeft: strings.vehiclePassedStop})
                }
                else
                {
                    this.setState({minutesLeft: nextProps.routeStops[0].arrives_in + ' ' + strings.minutes})
                }
            }
        }
        else if (this.state.fetchIntervalRunning)
        {
            this.setState({fetchIntervalRunning: false})
            clearInterval(this.fetchInterval)
        }
    }

    backAndroidHandler = () =>
    // when a user sends a stop request, the back button will be disabled
       {
        if (this.state.renderConfirm)
           {
            return false
        }
        else
           {
            return true
        }
    }

    componentWillUnmount()
       {
        BackAndroid.removeEventListener('hardwareBackPress', this.backAndroidHandler)
    }

    renderRouteInfo = () =>
    {
        return (this.state.renderConfirm ? <RouteInfo title={strings.aboutToStop} vehicleType={this.props.vehicle.vehicle_type} vehicleLine={this.props.vehicle.line} vehicleDestination={this.props.vehicle.destination} vehicleMinutesLeft={this.state.minutesLeft}/> : <RouteInfo title={strings.aboutToStop} vehicleType={this.props.vehicle.vehicle_type} vehicleLine={this.props.vehicle.line} vehicleDestination={this.props.vehicle.destination} vehicleMinutesLeft={this.state.minutesLeft}/>)
    }

    renderSlider = () =>
  {
        const sendStoprequest = () =>
        {
            this.props.sendStoprequest(this.props.vehicle.trip_id, this.props.stop.stopId, 'stop')
        }

        if (this.state.renderConfirm)
      {
            return (<SlideConfirmButton onSlideSuccess={sendStoprequest} text={strings.slide + ' →'} />)
        }
        else
      {
            return (
            <View style={styles.sliderBackgroundGreen}>
              <DefaultText style={styles.confirmedText}>{strings.stopsent}</DefaultText>
            </View>
            )
        }
    }

    renderButton = () =>
    {
        const goToStopRequestPage = () =>
      {
            Actions.routeStops({
                tripId: this.props.vehicle.trip_id,
                stopId: this.props.stop.stopId,
                vehicleLine: this.props.vehicle.line,
                vehicleDestination: this.props.vehicle.destination

            })
        }

        if (!this.state.renderConfirm)
        {
            return (
          <TouchableOpacity accessibilityComponentType="button" accessibilityLabel={strings.goToRouteStopsView} style={styles.goToRouteViewButton} onPress={goToStopRequestPage}>
            <DefaultText style={styles.goToRouteViewButtonText}>{strings.goToRouteStopsView}</DefaultText>
          </TouchableOpacity>)
        }
    }

    render()
  {
        return (
        <AccessibilityView style={styles.flex1} name="stopRequest">
          <BoldTitleBar title={strings.stopRequest}/>
          <TitleBar title={this.props.stop.stopName + '  (' + this.props.stop.stopCode + ')'} />
          <View style={styles.flex3}>
            {this.renderRouteInfo()}
          </View>
          <View style={styles.flex1}>
            {this.renderButton()}
          </View>
          {this.renderSlider()}
        </AccessibilityView>
        )
    }
}

const mapStateToProps = (state) =>
{
    return {
        sent: state.fetchReducer.sentStoprequest,
        routeStops: state.fetchRouteStopsReducer.routeStops,
        isFetchingStops: state.fetchRouteStopsReducer.isFetchingStops,
        routeIsReady: state.fetchRouteStopsReducer.routeIsReady,
        errorFetchingStops: state.fetchRouteStopsReducer.errorFetchingStops,
        error: state.fetchReducer.error,
        scene: state.routes.scene
    }
}

const mapDispatchToProps = (dispatch) =>
{
    return {
        sendStoprequest: (busId, stopId, requestType) =>
       {
            dispatch(sendStoprequest(busId, stopId, requestType))
        },
        fetchRouteStops: (tripId, BusId, current) =>
        {
            dispatch(fetchRouteStops(tripId, BusId, current))
        }
    }
}

StopRequestPage.propTypes = {
    fetchRouteStops: React.PropTypes.func.isRequired,
    vehicle: React.PropTypes.shape({
        trip_id: React.PropTypes.string.isRequired,
        vehicle_type: React.PropTypes.number.isRequired,
        line: React.PropTypes.string.isRequired,
        destination: React.PropTypes.string.isRequired,
        arrival: React.PropTypes.number.isRequired
    }),
    stop: React.PropTypes.shape({
        stopCode: React.PropTypes.string.isRequired,
        stopName: React.PropTypes.string.isRequired,
        stopId: React.PropTypes.string.isRequired
    }),
    sendStoprequest: React.PropTypes.func.isRequired,
    sent: React.PropTypes.bool.isRequired
}

export default connect(mapStateToProps, mapDispatchToProps)(StopRequestPage)
<commit_msg>Use props in StopRequestPage constructor<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { View, TouchableOpacity, BackAndroid } from 'react-native'
import { sendStoprequest } from '../actions/sendStoprequest'
import { Actions } from 'react-native-router-flux'

import { TitleBar, BoldTitleBar } from '../components/TitleBar'
import RouteInfo from '../components/RouteInfo'
import SlideConfirmButton from '../components/SlideConfirmButton'
import AccessibilityView from '../components/AccessibilityView'
import {DefaultText} from '../components/textComponents'

import styles from '../styles/stylesheet'
import strings from '../resources/translations'

import { fetchRouteStops } from '../actions/fetchRouteStops'

const UPDATE_INTERVAL_IN_SECS = 10

class StopRequestPage extends Component{
    constructor(props)
    {
        super(props)

        this.state = {
            renderConfirm: true,
            minutesLeft: this.props.vehicle.arrival + ' ' + strings.minutes,
            fetchIntervalRunning: false
        }

        this.sceneName = 'stopRequest'
    }

    createInterval = (props) =>
    {
        this.fetchInterval = setInterval(() =>
        {
            if (!props.isFetchingStops)
            {
                props.fetchRouteStops(this.props.vehicle.trip_id, this.props.stop.stopId, true)
            }
        }, UPDATE_INTERVAL_IN_SECS * 1000)
    }

    componentWillMount = () =>
    {
        this.props.fetchRouteStops(this.props.vehicle.trip_id, this.props.stop.stopId, true)
        this.setState({fetchIntervalRunning: true})
        this.createInterval(this.props)
    }

    componentWillReceiveProps = (nextProps) =>
      {
        this.setState({renderConfirm: !nextProps.sent})
        BackAndroid.addEventListener('hardwareBackPress', this.backAndroidHandler)

        if (nextProps.scene.name == this.sceneName)
        {
            if (!this.state.fetchIntervalRunning)
            {
                this.setState({fetchIntervalRunning: true})
                this.createInterval(nextProps)
            }
            if (typeof nextProps.routeStops[0] !== 'undefined' && nextProps.routeStops.length == 1)
            {
                if (nextProps.routeStops[0].arrives_in < 0)
                {
                    this.setState({minutesLeft: strings.vehiclePassedStop})
                }
                else
                {
                    this.setState({minutesLeft: nextProps.routeStops[0].arrives_in + ' ' + strings.minutes})
                }
            }
        }
        else if (this.state.fetchIntervalRunning)
        {
            this.setState({fetchIntervalRunning: false})
            clearInterval(this.fetchInterval)
        }
    }

    backAndroidHandler = () =>
    // when a user sends a stop request, the back button will be disabled
       {
        if (this.state.renderConfirm)
           {
            return false
        }
        else
           {
            return true
        }
    }

    componentWillUnmount()
       {
        BackAndroid.removeEventListener('hardwareBackPress', this.backAndroidHandler)
    }

    renderRouteInfo = () =>
    {
        return (this.state.renderConfirm ? <RouteInfo title={strings.aboutToStop} vehicleType={this.props.vehicle.vehicle_type} vehicleLine={this.props.vehicle.line} vehicleDestination={this.props.vehicle.destination} vehicleMinutesLeft={this.state.minutesLeft}/> : <RouteInfo title={strings.aboutToStop} vehicleType={this.props.vehicle.vehicle_type} vehicleLine={this.props.vehicle.line} vehicleDestination={this.props.vehicle.destination} vehicleMinutesLeft={this.state.minutesLeft}/>)
    }

    renderSlider = () =>
  {
        const sendStoprequest = () =>
        {
            this.props.sendStoprequest(this.props.vehicle.trip_id, this.props.stop.stopId, 'stop')
        }

        if (this.state.renderConfirm)
      {
            return (<SlideConfirmButton onSlideSuccess={sendStoprequest} text={strings.slide + ' →'} />)
        }
        else
      {
            return (
            <View style={styles.sliderBackgroundGreen}>
              <DefaultText style={styles.confirmedText}>{strings.stopsent}</DefaultText>
            </View>
            )
        }
    }

    renderButton = () =>
    {
        const goToStopRequestPage = () =>
      {
            Actions.routeStops({
                tripId: this.props.vehicle.trip_id,
                stopId: this.props.stop.stopId,
                vehicleLine: this.props.vehicle.line,
                vehicleDestination: this.props.vehicle.destination

            })
        }

        if (!this.state.renderConfirm)
        {
            return (
          <TouchableOpacity accessibilityComponentType="button" accessibilityLabel={strings.goToRouteStopsView} style={styles.goToRouteViewButton} onPress={goToStopRequestPage}>
            <DefaultText style={styles.goToRouteViewButtonText}>{strings.goToRouteStopsView}</DefaultText>
          </TouchableOpacity>)
        }
    }

    render()
  {
        return (
        <AccessibilityView style={styles.flex1} name="stopRequest">
          <BoldTitleBar title={strings.stopRequest}/>
          <TitleBar title={this.props.stop.stopName + '  (' + this.props.stop.stopCode + ')'} />
          <View style={styles.flex3}>
            {this.renderRouteInfo()}
          </View>
          <View style={styles.flex1}>
            {this.renderButton()}
          </View>
          {this.renderSlider()}
        </AccessibilityView>
        )
    }
}

const mapStateToProps = (state) =>
{
    return {
        sent: state.fetchReducer.sentStoprequest,
        routeStops: state.fetchRouteStopsReducer.routeStops,
        isFetchingStops: state.fetchRouteStopsReducer.isFetchingStops,
        routeIsReady: state.fetchRouteStopsReducer.routeIsReady,
        errorFetchingStops: state.fetchRouteStopsReducer.errorFetchingStops,
        error: state.fetchReducer.error,
        scene: state.routes.scene
    }
}

const mapDispatchToProps = (dispatch) =>
{
    return {
        sendStoprequest: (busId, stopId, requestType) =>
       {
            dispatch(sendStoprequest(busId, stopId, requestType))
        },
        fetchRouteStops: (tripId, BusId, current) =>
        {
            dispatch(fetchRouteStops(tripId, BusId, current))
        }
    }
}

StopRequestPage.propTypes = {
    fetchRouteStops: React.PropTypes.func.isRequired,
    vehicle: React.PropTypes.shape({
        trip_id: React.PropTypes.string.isRequired,
        vehicle_type: React.PropTypes.number.isRequired,
        line: React.PropTypes.string.isRequired,
        destination: React.PropTypes.string.isRequired,
        arrival: React.PropTypes.number.isRequired
    }),
    stop: React.PropTypes.shape({
        stopCode: React.PropTypes.string.isRequired,
        stopName: React.PropTypes.string.isRequired,
        stopId: React.PropTypes.string.isRequired
    }),
    sendStoprequest: React.PropTypes.func.isRequired,
    sent: React.PropTypes.bool.isRequired
}

export default connect(mapStateToProps, mapDispatchToProps)(StopRequestPage)
<|endoftext|>


<commit_before>$( document ).ready(function() {
  $( '.jshide' ).addClass('hidden').removeClass('jshide');
  $( '#date' ).bind('input', function(){
    //window.location.replace('index.php?date=' + $('#date').val());
    $.ajax({
      url: ('http://submit-iit-timesheet.geekkidconsulting.com/default.aspx?action=pull&date=' + $('#date').val()),
      crossDomain: true,
      xhrFields: {
        withCredentials: true
      },
      success: function(output, status, xhr) {
        alert(readcookie($('#date').val()) );
      },
      error: function() { $( '.hidden' ).addClass('.jshide').removeClass('hidden'); }
    });
  })
});
/*function setinfo(){
  alert( readcookie($('#date').val()) );
}*/
function readcookie(cookiename) {
  var realname = cookiename + "=";
  var cookarray = document.cookie.split(';');
  for(var i=0; i<cookarray.length; i++) {
    var resp = cookarray[i];
    while (resp.charAt(0)==' ') resp = resp.substring(1);
    if (resp.indexOf(realname) == 0) return resp.substring(realname.length,resp.length);
  }
  return "";
}<commit_msg>Added same cookie try even on error in ajax since cookie appears to come this way.<commit_after>$( document ).ready(function() {
  $( '.jshide' ).addClass('hidden').removeClass('jshide');
  $( '#date' ).bind('input', function(){
    //window.location.replace('index.php?date=' + $('#date').val());
    $.ajax({
      url: ('http://submit-iit-timesheet.geekkidconsulting.com/default.aspx?action=pull&date=' + $('#date').val()),
      crossDomain: true,
      xhrFields: {
        withCredentials: true
      },
      success: function(output, status, xhr) {
        alert(readcookie($('#date').val()) );
      },
      error: function(output, status, xhr) {
        alert(readcookie($('#date').val()) );
      },
    });
  })
});
/*function setinfo(){
  alert( readcookie($('#date').val()) );
}*/
function readcookie(cookiename) {
  var realname = cookiename + "=";
  var cookarray = document.cookie.split(';');
  for(var i=0; i<cookarray.length; i++) {
    var resp = cookarray[i];
    while (resp.charAt(0)==' ') resp = resp.substring(1);
    if (resp.indexOf(realname) == 0) return resp.substring(realname.length,resp.length);
  }
  return "";
}<|endoftext|>