<commit_before>import {Fragment} from "./fragment"

// ReplaceError:: class extends Error
// Error type raised by [`Node.replace`](#model.Node.replace) when
// given an invalid replacement.

export function ReplaceError(message) {
  let err = Error.call(this, message)
  err.__proto__ = ReplaceError.prototype
  return err
}

ReplaceError.prototype = Object.create(Error.prototype)
ReplaceError.prototype.constructor = ReplaceError
ReplaceError.prototype.name = "ReplaceError"

// ::- A slice represents a piece cut out of a larger document. It
// stores not only a fragment, but also the depth up to which nodes on
// both side are ‘open’ (cut through).
export class Slice {
  // :: (Fragment, number, number)
  // Create a slice. When specifying a non-zero open depth, you must
  // make sure that there are nodes of at least that depth at the
  // appropriate side of the fragment—i.e. if the fragment is an empty
  // paragraph node, `openStart` and `openEnd` can't be greater than 1.
  //
  // It is not necessary for the content of open nodes to conform to
  // the schema's content constraints, though it should be a valid
  // start/end/middle for such a node, depending on which sides are
  // open.
  constructor(content, openStart, openEnd) {
    // :: Fragment The slice's content.
    this.content = content
    // :: number The open depth at the start.
    this.openStart = openStart
    // :: number The open depth at the end.
    this.openEnd = openEnd
  }

  // :: number
  // The size this slice would add when inserted into a document.
  get size() {
    return this.content.size - this.openStart - this.openEnd
  }

  insertAt(pos, fragment) {
    let content = insertInto(this.content, pos + this.openStart, fragment, null)
    return content && new Slice(content, this.openStart, this.openEnd)
  }

  removeBetween(from, to) {
    return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd)
  }

  // :: (Slice) → bool
  // Tests whether this slice is equal to another slice.
  eq(other) {
    return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd
  }

  toString() {
    return this.content + "(" + this.openStart + "," + this.openEnd + ")"
  }

  // :: () → ?Object
  // Convert a slice to a JSON-serializable representation.
  toJSON() {
    if (!this.content.size) return null
    let json = {content: this.content.toJSON()}
    if (this.openStart > 0) json.openStart = this.openStart
    if (this.openEnd > 0) json.openEnd = this.openEnd
    return json
  }

  // :: (Schema, ?Object) → Slice
  // Deserialize a slice from its JSON representation.
  static fromJSON(schema, json) {
    if (!json) return Slice.empty
    return new Slice(Fragment.fromJSON(schema, json.content), json.openStart || 0, json.openEnd || 0)
  }

  // :: (Fragment) → Slice
  // Create a slice from a fragment by taking the maximum possible
  // open value on both side of the fragment.
  static maxOpen(fragment) {
    let openStart = 0, openEnd = 0
    for (let n = fragment.firstChild; n && !n.isLeaf; n = n.firstChild) openStart++
    for (let n = fragment.lastChild; n && !n.isLeaf; n = n.lastChild) openEnd++
    return new Slice(fragment, openStart, openEnd)
  }
}

function removeRange(content, from, to) {
  let {index, offset} = content.findIndex(from), child = content.maybeChild(index)
  let {index: indexTo, offset: offsetTo} = content.findIndex(to)
  if (offset == from || child.isText) {
    if (offsetTo != to && !content.child(indexTo).isText) throw new RangeError("Removing non-flat range")
    return content.cut(0, from).append(content.cut(to))
  }
  if (index != indexTo) throw new RangeError("Removing non-flat range")
  return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)))
}

function insertInto(content, dist, insert, parent) {
  let {index, offset} = content.findIndex(dist), child = content.maybeChild(index)
  if (offset == dist || child.isText) {
    if (parent && !parent.canReplace(index, index, insert)) return null
    return content.cut(0, dist).append(insert).append(content.cut(dist))
  }
  let inner = insertInto(child.content, dist - offset - 1, insert)
  return inner && content.replaceChild(index, child.copy(inner))
}

// :: Slice
// The empty slice.
Slice.empty = new Slice(Fragment.empty, 0, 0)

export function replace($from, $to, slice) {
  if (slice.openStart > $from.depth)
    throw new ReplaceError("Inserted content deeper than insertion position")
  if ($from.depth - slice.openStart != $to.depth - slice.openEnd)
    throw new ReplaceError("Inconsistent open depths")
  return replaceOuter($from, $to, slice, 0)
}

function replaceOuter($from, $to, slice, depth) {
  let index = $from.index(depth), node = $from.node(depth)
  if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {
    let inner = replaceOuter($from, $to, slice, depth + 1)
    return node.copy(node.content.replaceChild(index, inner))
  } else if (!slice.content.size) {
    return close(node, replaceTwoWay($from, $to, depth))
  } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case
    let parent = $from.parent, content = parent.content
    return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)))
  } else {
    let {start, end} = prepareSliceForReplace(slice, $from)
    return close(node, replaceThreeWay($from, start, end, $to, depth))
  }
}

function checkJoin(main, sub) {
  if (!sub.type.compatibleContent(main.type))
    throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name)
}

function joinable($before, $after, depth) {
  let node = $before.node(depth)
  checkJoin(node, $after.node(depth))
  return node
}

function addNode(child, target) {
  let last = target.length - 1
  if (last >= 0 && child.isText && child.sameMarkup(target[last]))
    target[last] = child.withText(target[last].text + child.text)
  else
    target.push(child)
}

function addRange($start, $end, depth, target) {
  let node = ($end || $start).node(depth)
  let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount
  if ($start) {
    startIndex = $start.index(depth)
    if ($start.depth > depth) {
      startIndex++
    } else if ($start.textOffset) {
      addNode($start.nodeAfter, target)
      startIndex++
    }
  }
  for (let i = startIndex; i < endIndex; i++) addNode(node.child(i), target)
  if ($end && $end.depth == depth && $end.textOffset)
    addNode($end.nodeBefore, target)
}

function close(node, content) {
  if (!node.type.validContent(content))
    throw new ReplaceError("Invalid content for node " + node.type.name)
  return node.copy(content)
}

function replaceThreeWay($from, $start, $end, $to, depth) {
  let openStart = $from.depth > depth && joinable($from, $start, depth + 1)
  let openEnd = $to.depth > depth && joinable($end, $to, depth + 1)

  let content = []
  addRange(null, $from, depth, content)
  if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
    checkJoin(openStart, openEnd)
    addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content)
  } else {
    if (openStart)
      addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content)
    addRange($start, $end, depth, content)
    if (openEnd)
      addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content)
  }
  addRange($to, null, depth, content)
  return new Fragment(content)
}

function replaceTwoWay($from, $to, depth) {
  let content = []
  addRange(null, $from, depth, content)
  if ($from.depth > depth) {
    let type = joinable($from, $to, depth + 1)
    addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content)
  }
  addRange($to, null, depth, content)
  return new Fragment(content)
}

function prepareSliceForReplace(slice, $along) {
  let extra = $along.depth - slice.openStart, parent = $along.node(extra)
  let node = parent.copy(slice.content)
  for (let i = extra - 1; i >= 0; i--)
    node = $along.node(i).copy(Fragment.from(node))
  return {start: node.resolveNoCache(slice.openStart + extra),
          end: node.resolveNoCache(node.content.size - slice.openEnd - extra)}
}
<commit_msg>Add an `openIsolating` argument to Slice.maxOpen<commit_after>import {Fragment} from "./fragment"

// ReplaceError:: class extends Error
// Error type raised by [`Node.replace`](#model.Node.replace) when
// given an invalid replacement.

export function ReplaceError(message) {
  let err = Error.call(this, message)
  err.__proto__ = ReplaceError.prototype
  return err
}

ReplaceError.prototype = Object.create(Error.prototype)
ReplaceError.prototype.constructor = ReplaceError
ReplaceError.prototype.name = "ReplaceError"

// ::- A slice represents a piece cut out of a larger document. It
// stores not only a fragment, but also the depth up to which nodes on
// both side are ‘open’ (cut through).
export class Slice {
  // :: (Fragment, number, number)
  // Create a slice. When specifying a non-zero open depth, you must
  // make sure that there are nodes of at least that depth at the
  // appropriate side of the fragment—i.e. if the fragment is an empty
  // paragraph node, `openStart` and `openEnd` can't be greater than 1.
  //
  // It is not necessary for the content of open nodes to conform to
  // the schema's content constraints, though it should be a valid
  // start/end/middle for such a node, depending on which sides are
  // open.
  constructor(content, openStart, openEnd) {
    // :: Fragment The slice's content.
    this.content = content
    // :: number The open depth at the start.
    this.openStart = openStart
    // :: number The open depth at the end.
    this.openEnd = openEnd
  }

  // :: number
  // The size this slice would add when inserted into a document.
  get size() {
    return this.content.size - this.openStart - this.openEnd
  }

  insertAt(pos, fragment) {
    let content = insertInto(this.content, pos + this.openStart, fragment, null)
    return content && new Slice(content, this.openStart, this.openEnd)
  }

  removeBetween(from, to) {
    return new Slice(removeRange(this.content, from + this.openStart, to + this.openStart), this.openStart, this.openEnd)
  }

  // :: (Slice) → bool
  // Tests whether this slice is equal to another slice.
  eq(other) {
    return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd
  }

  toString() {
    return this.content + "(" + this.openStart + "," + this.openEnd + ")"
  }

  // :: () → ?Object
  // Convert a slice to a JSON-serializable representation.
  toJSON() {
    if (!this.content.size) return null
    let json = {content: this.content.toJSON()}
    if (this.openStart > 0) json.openStart = this.openStart
    if (this.openEnd > 0) json.openEnd = this.openEnd
    return json
  }

  // :: (Schema, ?Object) → Slice
  // Deserialize a slice from its JSON representation.
  static fromJSON(schema, json) {
    if (!json) return Slice.empty
    return new Slice(Fragment.fromJSON(schema, json.content), json.openStart || 0, json.openEnd || 0)
  }

  // :: (Fragment, ?bool) → Slice
  // Create a slice from a fragment by taking the maximum possible
  // open value on both side of the fragment.
  static maxOpen(fragment, openIsolating=true) {
    let openStart = 0, openEnd = 0
    for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) openStart++
    for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) openEnd++
    return new Slice(fragment, openStart, openEnd)
  }
}

function removeRange(content, from, to) {
  let {index, offset} = content.findIndex(from), child = content.maybeChild(index)
  let {index: indexTo, offset: offsetTo} = content.findIndex(to)
  if (offset == from || child.isText) {
    if (offsetTo != to && !content.child(indexTo).isText) throw new RangeError("Removing non-flat range")
    return content.cut(0, from).append(content.cut(to))
  }
  if (index != indexTo) throw new RangeError("Removing non-flat range")
  return content.replaceChild(index, child.copy(removeRange(child.content, from - offset - 1, to - offset - 1)))
}

function insertInto(content, dist, insert, parent) {
  let {index, offset} = content.findIndex(dist), child = content.maybeChild(index)
  if (offset == dist || child.isText) {
    if (parent && !parent.canReplace(index, index, insert)) return null
    return content.cut(0, dist).append(insert).append(content.cut(dist))
  }
  let inner = insertInto(child.content, dist - offset - 1, insert)
  return inner && content.replaceChild(index, child.copy(inner))
}

// :: Slice
// The empty slice.
Slice.empty = new Slice(Fragment.empty, 0, 0)

export function replace($from, $to, slice) {
  if (slice.openStart > $from.depth)
    throw new ReplaceError("Inserted content deeper than insertion position")
  if ($from.depth - slice.openStart != $to.depth - slice.openEnd)
    throw new ReplaceError("Inconsistent open depths")
  return replaceOuter($from, $to, slice, 0)
}

function replaceOuter($from, $to, slice, depth) {
  let index = $from.index(depth), node = $from.node(depth)
  if (index == $to.index(depth) && depth < $from.depth - slice.openStart) {
    let inner = replaceOuter($from, $to, slice, depth + 1)
    return node.copy(node.content.replaceChild(index, inner))
  } else if (!slice.content.size) {
    return close(node, replaceTwoWay($from, $to, depth))
  } else if (!slice.openStart && !slice.openEnd && $from.depth == depth && $to.depth == depth) { // Simple, flat case
    let parent = $from.parent, content = parent.content
    return close(parent, content.cut(0, $from.parentOffset).append(slice.content).append(content.cut($to.parentOffset)))
  } else {
    let {start, end} = prepareSliceForReplace(slice, $from)
    return close(node, replaceThreeWay($from, start, end, $to, depth))
  }
}

function checkJoin(main, sub) {
  if (!sub.type.compatibleContent(main.type))
    throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name)
}

function joinable($before, $after, depth) {
  let node = $before.node(depth)
  checkJoin(node, $after.node(depth))
  return node
}

function addNode(child, target) {
  let last = target.length - 1
  if (last >= 0 && child.isText && child.sameMarkup(target[last]))
    target[last] = child.withText(target[last].text + child.text)
  else
    target.push(child)
}

function addRange($start, $end, depth, target) {
  let node = ($end || $start).node(depth)
  let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount
  if ($start) {
    startIndex = $start.index(depth)
    if ($start.depth > depth) {
      startIndex++
    } else if ($start.textOffset) {
      addNode($start.nodeAfter, target)
      startIndex++
    }
  }
  for (let i = startIndex; i < endIndex; i++) addNode(node.child(i), target)
  if ($end && $end.depth == depth && $end.textOffset)
    addNode($end.nodeBefore, target)
}

function close(node, content) {
  if (!node.type.validContent(content))
    throw new ReplaceError("Invalid content for node " + node.type.name)
  return node.copy(content)
}

function replaceThreeWay($from, $start, $end, $to, depth) {
  let openStart = $from.depth > depth && joinable($from, $start, depth + 1)
  let openEnd = $to.depth > depth && joinable($end, $to, depth + 1)

  let content = []
  addRange(null, $from, depth, content)
  if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
    checkJoin(openStart, openEnd)
    addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content)
  } else {
    if (openStart)
      addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content)
    addRange($start, $end, depth, content)
    if (openEnd)
      addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content)
  }
  addRange($to, null, depth, content)
  return new Fragment(content)
}

function replaceTwoWay($from, $to, depth) {
  let content = []
  addRange(null, $from, depth, content)
  if ($from.depth > depth) {
    let type = joinable($from, $to, depth + 1)
    addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content)
  }
  addRange($to, null, depth, content)
  return new Fragment(content)
}

function prepareSliceForReplace(slice, $along) {
  let extra = $along.depth - slice.openStart, parent = $along.node(extra)
  let node = parent.copy(slice.content)
  for (let i = extra - 1; i >= 0; i--)
    node = $along.node(i).copy(Fragment.from(node))
  return {start: node.resolveNoCache(slice.openStart + extra),
          end: node.resolveNoCache(node.content.size - slice.openEnd - extra)}
}
<|endoftext|>


<commit_before>var id;
var array;
var game;
var newTables;
var push = true;
var timeLock = false;
var lockTimer;
var lock = false;
var lockEnd = false;

function sync_sv() {
    socket.emit("get seated players");
    socket.on("chrono", function(i, str) {
        $("#chrono").html(str + '
' + i + ' sec remaining
to add more players');
        var chrono = setInterval(function() {
            i--;
            $("#sec").html(i);
            if (i == 0) {
                clearInterval(chrono);
            }
        }, 1000);
    });
    socket.on("chrono off", function() {
        $("#chrono").empty();
    });
    socket.on("action is true", function() {
        console.log('timeLock est true');
        timeLock = true;
    });
    socket.on("timer action", function(table) {
        var sec = 0;

        clearInterval(lockTimer);
        timeLock = false;
        lockTimer = setInterval(function() {
            sec++;
            if (timeLock && sec != 30) {
                clearInterval(lockTimer);
                timeLock = false;
            } else if (sec == 30) {
                sec = 0;
                clearInterval(lockTimer);
                timeLock = false;
                socket.emit("stop timer action", table);
            }
        }, 1000);
    });
    socket.on("seated players info", function(seat, seat_idx) {
        $("#qr" + seat_idx).css("visibility", "hidden");
        $("#qr_spot" + seat_idx).css("visibility", "hidden");
        $("#scan_msg" + seat_idx).css("visibility", "hidden");
        $("#player_name" + seat_idx).css("visibility", "visible");
        $("#player_name" + seat_idx).text(seat.player.nickname);
        $("#player_bankroll" + seat_idx).css("visibility", "visible");
        $("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + seat_idx).css("visibility", "visible");
    });
    socket.on("new player", function(player) {
        $("#qr" + player.seat_nb).css("visibility", "hidden");
        $("#qr_spot" + player.seat_nb).css("visibility", "hidden");
        $("#scan_msg" + player.seat_nb).css("visibility", "hidden");
        $("#player_name" + player.seat_nb).css("visibility", "visible");
        $("#player_name" + player.seat_nb).text(player.nickname);
        $("#player_bankroll" + player.seat_nb).css("visibility", "visible");
        $("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + player.seat_nb).css("visibility", "visible");
    });
    socket.on("kick player", function(seat_nb) {
        $("#qr" + seat_nb).css("visibility", "visible");
        $("#qr_spot" + seat_nb).css("visibility", "visible");
        $("#scan_msg" + seat_nb).css("visibility", "visible");
        $("#player_name" + seat_nb).css("visibility", "hidden");
        $("#player_name" + seat_nb).text("");
        $("#player_bankroll" + seat_nb).css("visibility", "hidden");
        $("#player_bankroll" + seat_nb).text("");
        $("#player_cards" + seat_nb).css("visibility", "hidden");
        $("#btn" + seat_nb).attr("src", "");
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
        $("#last_action" + seat_nb).css("visibility", "hidden");
    });
    socket.emit("ask buttons");
    socket.on("place button", function(type, seat_nb) {
        if (seat_nb <= 0 || seat_nb >= 7)
            return;
        if (type == "dealer") {
            $("#btn" + seat_nb).attr("src", "../img/Dealer.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "sb") {
            $("#btn" + seat_nb).attr("src", "../img/sb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "bb") {
            $("#btn" + seat_nb).attr("src", "../img/bb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        }
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("give cards", function(seat_nb) {
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("highlights", function(seat_idx, new_state) {
        var pos = $("#hSeat" + seat_idx);
        var idx;
        var pos_idx;

        if (new_state == "off") {
            for (idx = 1; idx <= 6; idx++) {
                pos_idx = $("#hSeat" + idx);
                pos_idx.hide();
                pos_idx.stop();
                pos_idx.css("width", "100%");
            }
        } else if (new_state == "on") {
            pos.show();
            pos.css("background-color", "#FE554C");
            pos.animate({
                "width": "0%"
            }, 31000);
        }
    });
    socket.on("i fold", function(decision, private_ids, zero) {
        console.log('I fold or I pass ok');
        socket.emit("player decision", decision, private_ids, zero);
    })
    socket.on("bankroll modification", function(seat_idx, player) {
        if (player.bankroll == "ALL IN")
            $("#player_bankroll" + seat_idx).text("ALL IN");
        else
            $("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
    });
    socket.on("pot modification", function(pot_amount) {
        $("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
    });
    socket.on("bet", function(seat_idx, amount) {
        if (!amount)
            $("#last_action" + seat_idx).text('');
        else {
            $("#last_action" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
        }
    });

    socket.on("last action", function(decision, seat_nb, amount) {
        amount == 0 ? amount = "" : amount = " " + amount + "$";
        var nick = $("#player_name" + seat_nb).text();
        var str = decision.split(" ");
        var text = "
" + nick + " " + str[0] + amount + "
";

        $("#last_action").text(nick + " " + str[0] + amount);
        $("#histoContent").empty();
        $("#histoContent").append(text);
    });
    socket.on("fold", function(seat_nb) {
        $("#seat" + seat_nb).css('opacity', '0.3');
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#bet_val" + seat_nb).text('');
        $("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
        $("#last_action" + seat_nb).text('FOLD');
    });
    socket.on("fold off", function() {
        var id;

        for (id = 1; id <= 6; id++) {
            $("#seat" + id).css('opacity', '1');
            $("#hSeat" + id).hide();
        }
    });
    socket.emit("get board");
    socket.on("send flop", function(card1, card2, card3) {
        $("#b1").attr("src", "img/cards/" + card1 + ".png");
        $("#b2").attr("src", "img/cards/" + card2 + ".png");
        $("#b3").attr("src", "img/cards/" + card3 + ".png");
        $("#b1, #b2, #b3").css("visibility", "visible");
    });
    socket.on("send turn", function(card4) {
        $("#b4").attr("src", "img/cards/" + card4 + ".png");
        $("#b4").css("visibility", "visible");
    });
    socket.on("send river", function(card5) {
        $("#b5").attr("src", "img/cards/" + card5 + ".png");
        $("#b5").css("visibility", "visible");
    });
    socket.on("remove last actions", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#last_action" + idx).remove();
    });
    socket.on("remove board", function() {
        $("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
        for (var idx = 1; idx <= 6; ++idx)
            $("#player_cards" + idx).attr("src", "../img/avatar.png");
        $("#last_action").text('');
    });
    socket.on("remove emplacements", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#btn" + idx).css("visibility", "hidden");
    });
    socket.on("show down", function(card1, card2, seat_nb) {
        if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
            if (card1 != -1 && card2 != -1) {
                $("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
                $("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
                $("#card1_" + seat_nb).css("visibility", "visible");
                $("#card2_" + seat_nb).css("visibility", "visible");
            } else {
                $("#card1_" + seat_nb).css("visibility", "hidden");
                $("#card2_" + seat_nb).css("visibility", "hidden");
            }
        }
    });
    socket.on("show down off", function(seat_nb) {
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
    });
    socket.on("winner", function(seat_nb, rank_name) {
        var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
        var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

        if (rank_name == "null")
            return;
        if (rank_name == 'disconnected') {
            $('#histoContent').empty();
            $('#histoContent').append(disconnect);
        } else if (seat_nb == 42 && rank_name == 'null') {
            $('#histoContent').empty();
            $('#histoContent').append('
Split !
');
        } else {
            $('#histoContent').empty();
            $('#histoContent').append(won);
        }
    });
    socket.on("win off", function() {
        $("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
    });
    socket.on("what is lock", function() {
        socket.emit("lock is true or false", lock);
    });
    socket.on("lock is true", function(vrai) {
        lock = vrai;
    })
    socket.on("lock is false", function(faux) {
        lock = faux;
    })
	socket.on("what is lock end", function() {
		socket.emit("lock is true or false", lockEnd);
	});
	socket.on("lock is true end", function(vrai) {
		lockEnd = vrai;
	})
	socket.on("lock is false end", function(faux) {
		lockEnd = faux;
	})
}

function check_timeLock(action) {
    timeLock = action;
}
<commit_msg>end tiemr<commit_after>var id;
var array;
var game;
var newTables;
var push = true;
var timeLock = false;
var lockTimer;
var lock = false;
var lockEnd = false;

function sync_sv() {
    socket.emit("get seated players");
    socket.on("chrono", function(i, str) {
        $("#chrono").html(str + '
' + i + ' sec remaining
to add more players');
        var chrono = setInterval(function() {
            i--;
            $("#sec").html(i);
            if (i == 0) {
                clearInterval(chrono);
            }
        }, 1000);
    });
    socket.on("chrono off", function() {
        $("#chrono").empty();
    });
    socket.on("action is true", function() {
        console.log('timeLock est true');
        timeLock = true;
    });
    socket.on("timer action", function(table) {
        var sec = 0;

        clearInterval(lockTimer);
        timeLock = false;
        lockTimer = setInterval(function() {
            sec++;
            if (timeLock && sec != 30) {
                clearInterval(lockTimer);
                timeLock = false;
            } else if (sec == 30) {
                sec = 0;
                clearInterval(lockTimer);
                timeLock = false;
                socket.emit("stop timer action", table);
            }
        }, 1000);
    });
    socket.on("seated players info", function(seat, seat_idx) {
        $("#qr" + seat_idx).css("visibility", "hidden");
        $("#qr_spot" + seat_idx).css("visibility", "hidden");
        $("#scan_msg" + seat_idx).css("visibility", "hidden");
        $("#player_name" + seat_idx).css("visibility", "visible");
        $("#player_name" + seat_idx).text(seat.player.nickname);
        $("#player_bankroll" + seat_idx).css("visibility", "visible");
        $("#player_bankroll" + seat_idx).text((Math.floor(+seat.player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + seat_idx).css("visibility", "visible");
    });
    socket.on("new player", function(player) {
        $("#qr" + player.seat_nb).css("visibility", "hidden");
        $("#qr_spot" + player.seat_nb).css("visibility", "hidden");
        $("#scan_msg" + player.seat_nb).css("visibility", "hidden");
        $("#player_name" + player.seat_nb).css("visibility", "visible");
        $("#player_name" + player.seat_nb).text(player.nickname);
        $("#player_bankroll" + player.seat_nb).css("visibility", "visible");
        $("#player_bankroll" + player.seat_nb).text((Math.floor(+player.bankroll * 100)) / 100 + "$");
        $("#player_cards" + player.seat_nb).css("visibility", "visible");
    });
    socket.on("kick player", function(seat_nb) {
        $("#qr" + seat_nb).css("visibility", "visible");
        $("#qr_spot" + seat_nb).css("visibility", "visible");
        $("#scan_msg" + seat_nb).css("visibility", "visible");
        $("#player_name" + seat_nb).css("visibility", "hidden");
        $("#player_name" + seat_nb).text("");
        $("#player_bankroll" + seat_nb).css("visibility", "hidden");
        $("#player_bankroll" + seat_nb).text("");
        $("#player_cards" + seat_nb).css("visibility", "hidden");
        $("#btn" + seat_nb).attr("src", "");
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
        $("#last_action" + seat_nb).css("visibility", "hidden");
    });
    socket.emit("ask buttons");
    socket.on("place button", function(type, seat_nb) {
        if (seat_nb <= 0 || seat_nb >= 7)
            return;
        if (type == "dealer") {
            $("#btn" + seat_nb).attr("src", "../img/Dealer.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "sb") {
            $("#btn" + seat_nb).attr("src", "../img/sb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        } else if (type == "bb") {
            $("#btn" + seat_nb).attr("src", "../img/bb.png")
            $("#btn" + seat_nb).css("visibility", "visible");
        }
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("give cards", function(seat_nb) {
        $("#player_cards" + seat_nb).attr("src", "../img/hidden_cards.png");
    });
    socket.on("highlights", function(seat_idx, new_state) {
        var pos = $("#hSeat" + seat_idx);
        var idx;
        var pos_idx;

        if (new_state == "off") {
            for (idx = 1; idx <= 6; idx++) {
                pos_idx = $("#hSeat" + idx);
                pos_idx.hide();
                pos_idx.stop();
                pos_idx.css("width", "100%");
            }
        } else if (new_state == "on") {
            pos.show();
            pos.css("background-color", "#FE554C");
            pos.animate({
                "width": "0%"
            }, 31000);
        }
    });
    socket.on("i fold", function(decision, private_ids, zero) {
        console.log('I fold or I pass ok');
        socket.emit("player decision", decision, private_ids, zero);
    })
    socket.on("bankroll modification", function(seat_idx, player) {
        if (player.bankroll == "ALL IN")
            $("#player_bankroll" + seat_idx).text("ALL IN");
        else
            $("#player_bankroll" + seat_idx).text((Math.floor(player.bankroll * 100)) / 100 + "$");
    });
    socket.on("pot modification", function(pot_amount) {
        $("#pot").text(Math.floor(+pot_amount * 100) / 100 + "$");
    });
    socket.on("bet", function(seat_idx, amount) {
        if (!amount)
            $("#last_action" + seat_idx).text('');
        else {
            $("#last_action" + seat_idx).text((Math.floor(amount * 100)) / 100 + "$");
        }
    });

    socket.on("last action", function(decision, seat_nb, amount) {
        amount == 0 ? amount = "" : amount = " " + amount + "$";
        var nick = $("#player_name" + seat_nb).text();
        var str = decision.split(" ");
        var text = "
" + nick + " " + str[0] + amount + "
";

        $("#last_action").text(nick + " " + str[0] + amount);
        $("#histoContent").empty();
        $("#histoContent").append(text);
    });
    socket.on("fold", function(seat_nb) {
        $("#seat" + seat_nb).css('opacity', '0.3');
        $("#btn" + seat_nb).css("visibility", "hidden");
        $("#bet_val" + seat_nb).text('');
        $("#player_cards" + seat_nb).attr("src", "../img/avatar.png");
        $("#last_action" + seat_nb).text('FOLD');
    });
    socket.on("fold off", function() {
        var id;

        for (id = 1; id <= 6; id++) {
            $("#seat" + id).css('opacity', '1');
            $("#hSeat" + id).hide();
        }
    });
    socket.emit("get board");
    socket.on("send flop", function(card1, card2, card3) {
        $("#b1").attr("src", "img/cards/" + card1 + ".png");
        $("#b2").attr("src", "img/cards/" + card2 + ".png");
        $("#b3").attr("src", "img/cards/" + card3 + ".png");
        $("#b1, #b2, #b3").css("visibility", "visible");
    });
    socket.on("send turn", function(card4) {
        $("#b4").attr("src", "img/cards/" + card4 + ".png");
        $("#b4").css("visibility", "visible");
    });
    socket.on("send river", function(card5) {
        $("#b5").attr("src", "img/cards/" + card5 + ".png");
        $("#b5").css("visibility", "visible");
    });
    socket.on("remove last actions", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#last_action" + idx).remove();
    });
    socket.on("remove board", function() {
        $("#b1, #b2, #b3, #b4, #b5").css("visibility", "hidden");
        for (var idx = 1; idx <= 6; ++idx)
            $("#player_cards" + idx).attr("src", "../img/avatar.png");
        $("#last_action").text('');
    });
    socket.on("remove emplacements", function() {
        for (var idx = 1; idx <= 6; ++idx)
            $("#btn" + idx).css("visibility", "hidden");
    });
    socket.on("show down", function(card1, card2, seat_nb) {
        if ($('#qr_spot' + seat_nb).css('visibility') == 'hidden') {
            if (card1 != -1 && card2 != -1) {
                $("#card1_" + seat_nb).attr("src", "../img/cards/" + card1 + ".png");
                $("#card2_" + seat_nb).attr("src", "../img/cards/" + card2 + ".png");
                $("#card1_" + seat_nb).css("visibility", "visible");
                $("#card2_" + seat_nb).css("visibility", "visible");
            } else {
                $("#card1_" + seat_nb).css("visibility", "hidden");
                $("#card2_" + seat_nb).css("visibility", "hidden");
            }
        }
    });
    socket.on("show down off", function(seat_nb) {
        $("#card1_" + seat_nb).css("visibility", "hidden");
        $("#card2_" + seat_nb).css("visibility", "hidden");
    });
    socket.on("winner", function(seat_nb, rank_name) {
        var disconnect = '
' + $("#player_name" + seat_nb).text() + ' won because player ' + rank_name + ' or folded
';
        var won = '
' + $("#player_name" + seat_nb).text() + ' won with ' + rank_name + '
';

        if (rank_name == "null")
            return;
        if (rank_name == 'disconnected') {
            $('#histoContent').empty();
            $('#histoContent').append(disconnect);
        } else if (seat_nb == 42 && rank_name == 'null') {
            $('#histoContent').empty();
            $('#histoContent').append('
Split !
');
        } else {
            $('#histoContent').empty();
            $('#histoContent').append(won);
        }
    });
    socket.on("win off", function() {
        $("#winner, #card1_1, #card2_1, #card1_2, #card2_2, #card1_3, #card2_3, #card1_4, #card2_4, #card1_5, #card2_5, #card1_6, #card2_6").css("visibility", "hidden");
    });
    socket.on("what is lock", function() {
        socket.emit("lock is true or false", lock);
    });
    socket.on("lock is true", function(vrai) {
        lock = vrai;
    })
    socket.on("lock is false", function(faux) {
        lock = faux;
    })
	socket.on("what is lock end", function() {
		socket.emit("lock is true or false end", lockEnd);
	});
	socket.on("lock is true end", function(vrai) {
		lockEnd = vrai;
	})
	socket.on("lock is false end", function(faux) {
		lockEnd = faux;
	})
}

function check_timeLock(action) {
    timeLock = action;
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HA<commit_msg>Fixing a typo added in the last readme update<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAI<|endoftext|>


<commit_before>window.cls || (window.cls = {});

/**
  * @constructor
  */
cls.Breakpoint = function(id, script_id, line_nr, event_type, active_rt_ids)
{
  this.id = id;
  this.script_id = script_id || "";
  this.line_nr = line_nr || 0;
  this.event_type = event_type || "";
  this.type = this.script_id ? "source" : "event";
  this.is_enabled = true;
  this.condition = "";
  this.update_is_active(active_rt_ids);
};

cls.Breakpoint.prototype = new function()
{
  this._is_active = true;

  this.__defineGetter__('is_active', function()
  {
    return this._is_active;
  });

  this.__defineSetter__('is_active', function(){});

  this.update_is_active = function(active_rt_ids)
  {
    if (this.script_id)
    {
      var rt_id = window.runtimes.getScriptsRuntimeId(this.script_id);
      this._is_active = active_rt_ids.indexOf(rt_id) != -1;
    }
  }
}

/**
  * @constructor
  */
cls.Breakpoints = function()
{

  if (cls.Breakpoints.instance)
  {
    return cls.Breakpoints.instance;
  }

  cls.Breakpoints.instance = this;

  /* interface */

  this.get_breakpoints = function(){};
  this.get_active_breakpoints = function(){};
  this.get_breakpoint_with_id = function(bp_id){};
  this.script_has_breakpoint_on_line = function(script_id, line_nr){};
  this.get_breakpoint_on_script_line = function(script_id, line_nr){};
  // bp_id optional
  this.add_breakpoint = function(script_id, line_nr, bp_id){};
  // removes the breakpoint in the host
  // disables the breakpoint in the client
  this.remove_breakpoint = function(script_id, line_nr){};
  this.delete_breakpoint = function(bp_id){};
  this.add_event_breakpoint = function(event_name){};
  this.remove_event_breakpoint = function(bp_id){};
  this.copy_breakpoints = function(new_script, old_script){};
  this.set_condition = function(condition, bp_id){};
  this.get_condition = function(bp_id){};

  /* constants */

  const
  BP_NONE = cls.NewScript.BP_NONE,
  BP_DISABLED = cls.NewScript.BP_DISABLED,
  BP_ENABLED = cls.NewScript.BP_ENABLED,
  BP_DELTA_ENABLE = BP_ENABLED - BP_DISABLED,
  BP_DELTA_CONDITION = cls.NewScript.BP_ENABLED_CONDITION - BP_ENABLED;

  /* private */

  this._get_bp_id = (function()
  {
    var count = 1;
    return function() {return count++;}
  })();

  this._add_bp = function(bp_id, script_id, line_nr, event_type)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      bp.is_enabled = true;
    }
    else
    {
      this._bps.push(new this._bp_class(bp_id,
                                        script_id,
                                        line_nr,
                                        event_type,
                                        this._active_rt_ids));
    }
    window.messages.post("breakpoint-updated",
                         {id: bp_id, script_id: script_id});
  };

  this._remove_bp = function(bp_id)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      bp.is_enabled = false;
      window.messages.post("breakpoint-updated",
                           {id: bp.id, script_id: bp.script_id});
    }
  };

  this._get_bp_id_with_script_id_and_line_nr = function(script_id, line_nr)
  {
    for (var i = 0, bp; bp = this._bps[i]; i++)
    {
      if (bp.script_id == script_id && bp.line_nr == line_nr)
      {
        return bp.id;
      }
    }
    return 0;
  };

  this._update_bp_state = function(bp, delta, absolute)
  {
    var script = bp && window.runtimes.getScript(bp.script_id);
    if (script)
    {
      if (delta)
      {
        script.breakpoint_states[bp.line_nr] += delta;
      }
      else
      {
        script.breakpoint_states[bp.line_nr] = absolute;
      }
    }
    window.messages.post('breakpoint-updated',
                         {id: bp.id,
                          script_id: bp.script_id,
                          event_type: bp.event_type});
  };

  this._get_bp_id_with_event_name = function(event_name)
  {
    for (var i = 0, bp; bp = this._bps[i]; i++)
    {
      if (bp.event_type == event_name)
      {
        return bp.id;
      }
    }
    return 0;
  };

  this._replace_script_id = function(new_script_id, old_script_id)
  {
    for (var i = 0, bp; bp = this._bps[i]; i++)
    {
      if (bp.script_id == old_script_id)
      {
        bp.script_id = new_script_id;
        bp.update_is_active(this._active_rt_ids);
      }
    }
  };

  this._get_bp_index_with_bp_id = function(bp_id)
  {
    for (var i = 0; i < this._bps.length && this._bps[i].id != bp_id; i++);
    return i;
  };

  this._on_active_tab = function(msg)
  {
    this._active_rt_ids = msg.activeTab;
    this._bps.forEach(function(bp)
    {
      bp.update_is_active(this._active_rt_ids);
    }, this);
    window.views.breakpoints.update();
  };

  this._init = function()
  {
    this._bps = [];
    this._bp_class = window.cls.Breakpoint;
    this._esdb = window.services['ecmascript-debugger'];
    this._active_rt_ids = [];
    window.messages.addListener('active-tab', this._on_active_tab.bind(this));
  };

  /* implementation */

  this.get_breakpoints = function()
  {
    return this._bps;
  };

  this.get_active_breakpoints = function()
  {
    return this._bps.filter(function(bp)
    {
      return bp.is_active;
    });
  };

  this.get_breakpoint_with_id = function(bp_id)
  {
    return this._bps[this._get_bp_index_with_bp_id(bp_id)];
  };

  this.add_breakpoint = function(script_id, line_nr, bp_id)
  {
    var script = window.runtimes.getScript(script_id);
    if (script)
    {
      bp_id = bp_id ||
              // if a breakpoint was set on the same script and line before
              this._get_bp_id_with_script_id_and_line_nr(script_id, line_nr) ||
              this._get_bp_id();
      script.breakpoints[line_nr] = bp_id;
      if (!script.breakpoint_states[line_nr])
      {
        script.breakpoint_states[line_nr] = BP_DISABLED;
      }
      if (script.breakpoint_states[line_nr] < BP_ENABLED)
      {
        script.breakpoint_states[line_nr] += BP_DELTA_ENABLE;
      }
      // message signature has changes with version 6.0
      // AddBreakpoint means always to a source line
      // for events it's now AddEventBreakpoint
      if (this._esdb.major_version > 5)
      {
        this._esdb.requestAddBreakpoint(0, [bp_id, script_id, line_nr]);
      }
      else
      {
        this._esdb.requestAddBreakpoint(0, [bp_id, "line", script_id, line_nr]);
      }
      this._add_bp(bp_id, script_id, line_nr);
    }
  };

  this.remove_breakpoint = function(script_id, line_nr)
  {
    var script = window.runtimes.getScript(script_id);
    if (script)
    {
      var bp_id = script.breakpoints[line_nr];
      this._esdb.requestRemoveBreakpoint(0, [bp_id]);
      script.breakpoints[line_nr] = 0;
      if (script.breakpoint_states[line_nr] >= BP_ENABLED)
      {
        script.breakpoint_states[line_nr] -= BP_DELTA_ENABLE;
      }
      this._remove_bp(bp_id);
      return bp_id;
    }
  };

  this.delete_breakpoint = function(bp_id)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    this._bps.splice(this._get_bp_index_with_bp_id(bp_id), 1);
    this._update_bp_state(bp, 0, BP_NONE);
  };

  this.add_event_breakpoint = function(event_name)
  {
    var bp_id = this._get_bp_id_with_event_name(event_name) ||
                this._get_bp_id();
    this._esdb.requestAddEventBreakpoint(0, [bp_id, event_name]);
    this._add_bp(bp_id, null, null, event_name);
    return bp_id;
  };

  this.remove_event_breakpoint = function(bp_id)
  {
    this._esdb.requestRemoveBreakpoint(0, [bp_id]);
    this._remove_bp(bp_id);
  };

  this.copy_breakpoints = function(new_script, old_script)
  {
    new_script.breakpoint_states = old_script.breakpoint_states;
    this._replace_script_id(new_script.script_id, old_script.script_id);
    var old_bps = old_script.breakpoints;
    for (line_nr in old_bps)
    {
      if (old_bps[line_nr])
      {
        line_nr = parseInt(line_nr);
        this.remove_breakpoint(old_script.script_id, line_nr);
        this.add_breakpoint(new_script.script_id, line_nr, old_bps[line_nr]);
      }
    }
  };

  this.script_has_breakpoint_on_line = function(script_id, line_nr)
  {
    var script = window.runtimes.getScript(script_id);
    return Boolean(script && script.breakpoints[line_nr]);
  };

  this.get_breakpoint_on_script_line = function(script_id, line_nr)
  {
    var bp_id = this._get_bp_id_with_script_id_and_line_nr(script_id, line_nr);
    return bp_id ? this.get_breakpoint_with_id(bp_id): null;
  };

  this.set_condition = function(condition, bp_id)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      var current_condition = bp.condition;
      bp.condition = condition;
      if (condition && !current_condition)
      {
        this._update_bp_state(bp, BP_DELTA_CONDITION);
      }
      else if(!condition && current_condition)
      {
        this._update_bp_state(bp, -BP_DELTA_CONDITION);
      }
    }
  };

  this.get_condition = function(bp_id)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    return bp && bp.condition || "";
  };

  /* instantiation */

  this._init();

};

cls.Breakpoints.get_instance = function()
{
  return this.instance || new cls.Breakpoints();
};
<commit_msg>Fix for DFL-1780, Adding a breakpoint to a line where execution has stopped because of event breakpoint goes wrong.<commit_after>window.cls || (window.cls = {});

/**
  * @constructor
  */
cls.Breakpoint = function(id, script_id, line_nr, event_type, active_rt_ids)
{
  this.id = id;
  this.script_id = script_id || "";
  this.line_nr = line_nr || 0;
  this.event_type = event_type || "";
  this.type = this.script_id ? "source" : "event";
  this.is_enabled = true;
  this.condition = "";
  this.update_is_active(active_rt_ids);
};

cls.Breakpoint.prototype = new function()
{
  this._is_active = true;

  this.__defineGetter__('is_active', function()
  {
    return this._is_active;
  });

  this.__defineSetter__('is_active', function(){});

  this.update_is_active = function(active_rt_ids)
  {
    if (this.script_id)
    {
      var rt_id = window.runtimes.getScriptsRuntimeId(this.script_id);
      this._is_active = active_rt_ids.indexOf(rt_id) != -1;
    }
  }
}

/**
  * @constructor
  */
cls.Breakpoints = function()
{

  if (cls.Breakpoints.instance)
  {
    return cls.Breakpoints.instance;
  }

  cls.Breakpoints.instance = this;

  /* interface */

  this.get_breakpoints = function(){};
  this.get_active_breakpoints = function(){};
  this.get_breakpoint_with_id = function(bp_id){};
  this.script_has_breakpoint_on_line = function(script_id, line_nr){};
  this.get_breakpoint_on_script_line = function(script_id, line_nr){};
  // bp_id optional
  this.add_breakpoint = function(script_id, line_nr, bp_id){};
  // removes the breakpoint in the host
  // disables the breakpoint in the client
  this.remove_breakpoint = function(script_id, line_nr){};
  this.delete_breakpoint = function(bp_id){};
  this.add_event_breakpoint = function(event_name){};
  this.remove_event_breakpoint = function(bp_id){};
  this.copy_breakpoints = function(new_script, old_script){};
  this.set_condition = function(condition, bp_id){};
  this.get_condition = function(bp_id){};

  /* constants */

  const
  BP_NONE = cls.NewScript.BP_NONE,
  BP_DISABLED = cls.NewScript.BP_DISABLED,
  BP_ENABLED = cls.NewScript.BP_ENABLED,
  BP_DELTA_ENABLE = BP_ENABLED - BP_DISABLED,
  BP_DELTA_CONDITION = cls.NewScript.BP_ENABLED_CONDITION - BP_ENABLED;

  /* private */

  this._get_bp_id = (function()
  {
    var count = 1;
    return function() {return count++;}
  })();

  this._add_bp = function(bp_id, script_id, line_nr, event_type)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      bp.is_enabled = true;
    }
    else
    {
      this._bps.push(new this._bp_class(bp_id,
                                        script_id,
                                        line_nr,
                                        event_type,
                                        this._active_rt_ids));
    }
    window.messages.post("breakpoint-updated",
                         {id: bp_id, script_id: script_id});
  };

  this._remove_bp = function(bp_id)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      bp.is_enabled = false;
      window.messages.post("breakpoint-updated",
                           {id: bp.id, script_id: bp.script_id});
    }
  };

  this._get_bp_id_with_script_id_and_line_nr = function(script_id, line_nr)
  {
    for (var i = 0, bp; bp = this._bps[i]; i++)
    {
      if (bp.script_id == script_id && bp.line_nr == line_nr)
      {
        return bp.id;
      }
    }
    return 0;
  };

  this._update_bp_state = function(bp, delta, absolute)
  {
    var script = bp && window.runtimes.getScript(bp.script_id);
    if (script)
    {
      if (delta)
      {
        script.breakpoint_states[bp.line_nr] += delta;
      }
      else
      {
        var state = script.breakpoint_states[bp.line_nr] || 0;
        var pointer_state = state % 3;
        script.breakpoint_states[bp.line_nr] = absolute;
        script.breakpoint_states[bp.line_nr] += pointer_state;
      }
    }
    window.messages.post('breakpoint-updated',
                         {id: bp.id,
                          script_id: bp.script_id,
                          event_type: bp.event_type});
  };

  this._get_bp_id_with_event_name = function(event_name)
  {
    for (var i = 0, bp; bp = this._bps[i]; i++)
    {
      if (bp.event_type == event_name)
      {
        return bp.id;
      }
    }
    return 0;
  };

  this._replace_script_id = function(new_script_id, old_script_id)
  {
    for (var i = 0, bp; bp = this._bps[i]; i++)
    {
      if (bp.script_id == old_script_id)
      {
        bp.script_id = new_script_id;
        bp.update_is_active(this._active_rt_ids);
      }
    }
  };

  this._get_bp_index_with_bp_id = function(bp_id)
  {
    for (var i = 0; i < this._bps.length && this._bps[i].id != bp_id; i++);
    return i;
  };

  this._on_active_tab = function(msg)
  {
    this._active_rt_ids = msg.activeTab;
    this._bps.forEach(function(bp)
    {
      bp.update_is_active(this._active_rt_ids);
    }, this);
    window.views.breakpoints.update();
  };

  this._init = function()
  {
    this._bps = [];
    this._bp_class = window.cls.Breakpoint;
    this._esdb = window.services['ecmascript-debugger'];
    this._active_rt_ids = [];
    window.messages.addListener('active-tab', this._on_active_tab.bind(this));
  };

  /* implementation */

  this.get_breakpoints = function()
  {
    return this._bps;
  };

  this.get_active_breakpoints = function()
  {
    return this._bps.filter(function(bp)
    {
      return bp.is_active;
    });
  };

  this.get_breakpoint_with_id = function(bp_id)
  {
    return this._bps[this._get_bp_index_with_bp_id(bp_id)];
  };

  this.add_breakpoint = function(script_id, line_nr, bp_id)
  {
    var script = window.runtimes.getScript(script_id);
    if (script)
    {
      bp_id = bp_id ||
              // if a breakpoint was set on the same script and line before
              this._get_bp_id_with_script_id_and_line_nr(script_id, line_nr) ||
              this._get_bp_id();
      script.breakpoints[line_nr] = bp_id;
      var state = script.breakpoint_states[line_nr] || 0;
      var pointer_state = state % 3;
      state -= pointer_state;
      if (!state)
      {
        script.breakpoint_states[line_nr] = BP_DISABLED;
      }
      if (script.breakpoint_states[line_nr] < BP_ENABLED)
      {
        script.breakpoint_states[line_nr] += BP_DELTA_ENABLE;
      }
      script.breakpoint_states[line_nr] += pointer_state;
      // message signature has changes with version 6.0
      // AddBreakpoint means always to a source line
      // for events it's now AddEventBreakpoint
      if (this._esdb.major_version > 5)
      {
        this._esdb.requestAddBreakpoint(0, [bp_id, script_id, line_nr]);
      }
      else
      {
        this._esdb.requestAddBreakpoint(0, [bp_id, "line", script_id, line_nr]);
      }
      this._add_bp(bp_id, script_id, line_nr);
    }
  };

  this.remove_breakpoint = function(script_id, line_nr)
  {
    var script = window.runtimes.getScript(script_id);
    if (script)
    {
      var bp_id = script.breakpoints[line_nr];
      this._esdb.requestRemoveBreakpoint(0, [bp_id]);
      script.breakpoints[line_nr] = 0;
      var state = script.breakpoint_states[line_nr] || 0;
      var pointer_state = state % 3;
      state -= pointer_state;
      if (state >= BP_ENABLED)
      {
        script.breakpoint_states[line_nr] = state - BP_DELTA_ENABLE;
      }
      script.breakpoint_states[line_nr] += pointer_state;
      this._remove_bp(bp_id);
      return bp_id;
    }
  };

  this.delete_breakpoint = function(bp_id)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    this._bps.splice(this._get_bp_index_with_bp_id(bp_id), 1);
    this._update_bp_state(bp, 0, BP_NONE);
  };

  this.add_event_breakpoint = function(event_name)
  {
    var bp_id = this._get_bp_id_with_event_name(event_name) ||
                this._get_bp_id();
    this._esdb.requestAddEventBreakpoint(0, [bp_id, event_name]);
    this._add_bp(bp_id, null, null, event_name);
    return bp_id;
  };

  this.remove_event_breakpoint = function(bp_id)
  {
    this._esdb.requestRemoveBreakpoint(0, [bp_id]);
    this._remove_bp(bp_id);
  };

  this.copy_breakpoints = function(new_script, old_script)
  {
    new_script.breakpoint_states = old_script.breakpoint_states;
    this._replace_script_id(new_script.script_id, old_script.script_id);
    var old_bps = old_script.breakpoints;
    for (line_nr in old_bps)
    {
      if (old_bps[line_nr])
      {
        line_nr = parseInt(line_nr);
        this.remove_breakpoint(old_script.script_id, line_nr);
        this.add_breakpoint(new_script.script_id, line_nr, old_bps[line_nr]);
      }
    }
  };

  this.script_has_breakpoint_on_line = function(script_id, line_nr)
  {
    var script = window.runtimes.getScript(script_id);
    return Boolean(script && script.breakpoints[line_nr]);
  };

  this.get_breakpoint_on_script_line = function(script_id, line_nr)
  {
    var bp_id = this._get_bp_id_with_script_id_and_line_nr(script_id, line_nr);
    return bp_id ? this.get_breakpoint_with_id(bp_id): null;
  };

  this.set_condition = function(condition, bp_id)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    if (bp)
    {
      var current_condition = bp.condition;
      bp.condition = condition;
      if (condition && !current_condition)
      {
        this._update_bp_state(bp, BP_DELTA_CONDITION);
      }
      else if(!condition && current_condition)
      {
        this._update_bp_state(bp, -BP_DELTA_CONDITION);
      }
    }
  };

  this.get_condition = function(bp_id)
  {
    var bp = this.get_breakpoint_with_id(bp_id);
    return bp && bp.condition || "";
  };

  /* instantiation */

  this._init();

};

cls.Breakpoints.get_instance = function()
{
  return this.instance || new cls.Breakpoints();
};
<|endoftext|>


<commit_before>/* eslint no-var: 0, babel/object-shorthand: 0, vars-on-top: 0 */
require('babel/register');

var webpack = require('webpack');
var path = require('path');

var isCI = process.env.CI === 'true';
var devBrowser = process.env.PHANTOM ? 'PhantomJS' : 'Chrome';

module.exports = function(config) {
  config.set({

    frameworks: [
      'mocha',
      'sinon-chai'
    ],

    files: [
      'tests.webpack.js'
    ],

    preprocessors: {
      'tests.webpack.js': ['webpack', 'sourcemap']
    },

    reporters: ['mocha'],

    port: 9876,

    colors: true,

    logLevel: config.LOG_INFO,

    autoWatch: true,

    browsers: [isCI ? 'ChromeTravisCI' : devBrowser],

    customLaunchers: {
      ChromeTravisCI: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    captureTimeout: 60000,
    browserNoActivityTimeout: 45000,

    singleRun: isCI,

    webpack: {

      output: {
        pathInfo: true
      },

      webpackServer: {
        noInfo: true
      },

      resolve: {
        extensions: ['', '.js', '.json', '.jsx'],
        modulesDirectories: ['node_modules', 'app'],
        alias: {
          lib: path.join(__dirname, 'lib'),
          globals: path.join(__dirname, 'globals'),
          components: path.join(__dirname, 'components')
        }
      },

      module: {
        loaders: [{
          test: /\.js$/,
          loader: 'babel?cacheDirectory',
          exclude: /node_modules/
        }, {
          test: /\.css$/,
          loader: 'css-loader/locals?modules'
        }, {
          test: /\.(gif|png|jpe?g)$/,
          loaders: [
            'file?hash=sha512&digest=hex&name=[hash].[ext]',
            'image-webpack?optimizationLevel=7&interlaced=false&progressive=true'
          ]
        }, {
          test: /\.(woff|woff2|eot|ttf)$/,
          loader: 'url?limit=10000&name=[sha512:hash:base64:7].[ext]'
        }, {
          test: /\.svg$/,
          exclude: /icons\/.+\.svg$/, // exclude all icons inside /icons folder
          loader: 'url-loader!svgo-loader?useConfig=svgoConfig'
        }, {
          test: /icons\/.+\.svg$/,
          loader: 'raw-loader!svgo-loader?useConfig=svgoConfig'
        }]
      },

      svgoConfig: {
        plugins: [{
          removeAttrs: {
            attrs: '(width|height)'
          }
        }, {
          mergePaths: false
        }, {
          cleanupIDs: false
        }]
      },

      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: JSON.stringify('development')
          }
        })
      ],
      devTool: 'inline-source-map'
    }
  });

  if (isCI) {
    config.sngleRun = true;
    config.reporters = ['dots'];
  }
};
<commit_msg>Remove phantom from karma conf<commit_after>/* eslint no-var: 0, babel/object-shorthand: 0, vars-on-top: 0 */
require('babel/register');

var webpack = require('webpack');
var path = require('path');

var isCI = process.env.CI === 'true';

module.exports = function(config) {
  config.set({

    frameworks: [
      'mocha',
      'sinon-chai'
    ],

    files: [
      'tests.webpack.js'
    ],

    preprocessors: {
      'tests.webpack.js': ['webpack', 'sourcemap']
    },

    reporters: ['mocha'],

    port: 9876,

    colors: true,

    logLevel: config.LOG_INFO,

    autoWatch: true,

    browsers: ['Chrome'],

    customLaunchers: {
      ChromeTravisCI: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    captureTimeout: 60000,
    browserNoActivityTimeout: 45000,

    singleRun: isCI,

    webpack: {

      output: {
        pathInfo: true
      },

      webpackServer: {
        noInfo: true
      },

      resolve: {
        extensions: ['', '.js', '.json', '.jsx'],
        modulesDirectories: ['node_modules', 'app'],
        alias: {
          lib: path.join(__dirname, 'lib'),
          globals: path.join(__dirname, 'globals'),
          components: path.join(__dirname, 'components')
        }
      },

      module: {
        loaders: [{
          test: /\.js$/,
          loader: 'babel?cacheDirectory',
          exclude: /node_modules/
        }, {
          test: /\.css$/,
          loader: 'css-loader/locals?modules'
        }, {
          test: /\.(gif|png|jpe?g)$/,
          loaders: [
            'file?hash=sha512&digest=hex&name=[hash].[ext]',
            'image-webpack?optimizationLevel=7&interlaced=false&progressive=true'
          ]
        }, {
          test: /\.(woff|woff2|eot|ttf)$/,
          loader: 'url?limit=10000&name=[sha512:hash:base64:7].[ext]'
        }, {
          test: /\.svg$/,
          exclude: /icons\/.+\.svg$/, // exclude all icons inside /icons folder
          loader: 'url-loader!svgo-loader?useConfig=svgoConfig'
        }, {
          test: /icons\/.+\.svg$/,
          loader: 'raw-loader!svgo-loader?useConfig=svgoConfig'
        }]
      },

      svgoConfig: {
        plugins: [{
          removeAttrs: {
            attrs: '(width|height)'
          }
        }, {
          mergePaths: false
        }, {
          cleanupIDs: false
        }]
      },

      plugins: [
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: JSON.stringify('development')
          }
        })
      ],
      devTool: 'inline-source-map'
    }
  });

  if (isCI) {
    config.sngleRun = true;
    config.reporters = ['dots'];
  }
};
<|endoftext|>


<commit_before>import { patchLocation, search } from "./";

export default toggleSearch;

export const type = "TOGGLE_SEARCH_ENABLED";

function toggleSearch(payload = {}) {
  return (dispatch, getState) => {
    const state = getState();

    if (payload.sync) {
      focus(state.searchEnabled);
      return;
    }

    const next = "focus" in payload ? payload.focus : !state.searchEnabled;

    if (!next) {
      dispatch(search({ persist: true, value: value() }));
    }

    dispatch(
      patchLocation({ query: { "search-enabled": next, "search-preview": 0 } })
    );
  };
}

toggleSearch.type = type;
toggleSearch.key = "search-enabled";
toggleSearch.property = "searchEnabled";

function focus(next) {
  if (!next) {
    return;
  }

  if (!("document" in global)) {
    return;
  }

  setTimeout(() => {
    const el = global.document.query("input[data-search]");

    if (!el) {
      return;
    }

    if (global.document.activeElement !== el) {
      el.focus();
    }

    const range = el.value.length;
    el.setSelectionRange(range, range);
  }, 100);
}

function value() {
  if (!("document" in global)) {
    return;
  }

  const el = global.document.query("input[data-search]");

  if (!el) {
    return;
  }

  return el.value;
}
<commit_msg>fix: search toggle by using document.querySelector<commit_after>import { patchLocation, search } from "./";

export default toggleSearch;

export const type = "TOGGLE_SEARCH_ENABLED";

function toggleSearch(payload = {}) {
  return (dispatch, getState) => {
    const state = getState();

    if (payload.sync) {
      focus(state.searchEnabled);
      return;
    }

    const next = "focus" in payload ? payload.focus : !state.searchEnabled;

    if (!next) {
      dispatch(search({ persist: true, value: value() }));
    }

    dispatch(
      patchLocation({ query: { "search-enabled": next, "search-preview": 0 } })
    );
  };
}

toggleSearch.type = type;
toggleSearch.key = "search-enabled";
toggleSearch.property = "searchEnabled";

function focus(next) {
  if (!next) {
    return;
  }

  if (!("document" in global)) {
    return;
  }

  setTimeout(() => {
    const el = global.document.querySelector("input[data-search]");

    if (!el) {
      return;
    }

    if (global.document.activeElement !== el) {
      el.focus();
    }

    const range = el.value.length;
    el.setSelectionRange(range, range);
  }, 100);
}

function value() {
  if (!("document" in global)) {
    return;
  }

  const el = global.document.querySelector("input[data-search]");

  if (!el) {
    return;
  }

  return el.value;
}
<|endoftext|>


<commit_before>'use strict';

/*
* The original C++ code and copyright notice is from the [Boost library]{http://www.boost.org/doc/libs/1_64_0/boost/math/special_functions/beta.hpp}.
*
* The implementation has been modified for JavaScript.
*/

/*
* (C) Copyright John Maddock 2006.
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var evalrational = require( '@stdlib/math/base/tools/evalrational' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var pow = require( '@stdlib/math/base/special/pow' );
var E = require( '@stdlib/math/constants/float64-e' );
var EPSILON = require( '@stdlib/math/constants/float64-eps' );

// VARIABLES //

var G = 10.90051099999999983936049829935654997826;
var NUM = [
	709811.662581657956893540610814842699825,
	679979.847415722640161734319823103390728,
	293136.785721159725251629480984140341656,
	74887.5403291467179935942448101441897121,
	12555.29058241386295096255111537516768137,
	1443.42992444170669746078056942194198252,
	115.2419459613734722083208906727972935065,
	6.30923920573262762719523981992008976989,
	0.2266840463022436475495508977579735223818,
	0.004826466289237661857584712046231435101741,
	0.4624429436045378766270459638520555557321e-4
];
var DENOM = [
	0,
	362880,
	1026576,
	1172700,
	723680,
	269325,
	63273,
	9450,
	870,
	45,
	1
];

// FUNCTIONS //

/**
* Calculate the Lanczos approximation scaled by exp(G).
*
* @private
* @param {number} z - input value
* @returns {number} Lanczos approximation
*/
var lanczosSumExpGScaled = evalrational( NUM, DENOM );

// MAIN //

/**
* Evaluate the beta function.
*
* @param {NonNegativeNumber} a - input value
* @param {NonNegativeNumber} b - input value
* @returns {number} evaluated beta function
*
* @example
* var v = beta( 0, 0 );
* // returns Number.POSITIVE_INFINITY
*
* @example
* var v = beta( 1, 1 );
* // returns 1
*
* @example
* var v = beta( -1, 2 );
* // returns NaN
*
* @example
* var v = beta( 5, 0.2 );
* // returns ~3.382
*
* @example
* var v = beta( 4, 1 );
* // returns 0.25
*
* @example
* var v = beta( NaN, 2 );
* // returns NaN
*/
function beta( a, b ) {
	var prefix;
	var ambh;
	var agh;
	var bgh;
	var cgh;
	var res;
	var tmp;
	var c;

	prefix = 1;
	c = a + b;
	if ( isnan( a ) || isnan( b ) ) {
		return NaN;
	}
	if ( a < 0.0 || b < 0.0 ) {
		return NaN;
	}
	if ( b === 1.0 ) {
		return 1.0 / a;
	} else if ( a === 1.0 ) {
		return 1.0 / b;
	} else if ( c < EPSILON ) {
		res = c / a;
		res /= b;
		return res;
	}

	// Special cases:
	if ( c === a && b < EPSILON ) {
		return 1.0 / b;
	} else if ( c === b && a < EPSILON ) {
		return 1.0 / a;
	}

	if ( a < b ) {
		// Swap a and b:
		tmp = b;
		b = a;
		a = tmp;
	}

	// Lanczos calculation:
	agh = a + G - 0.5;
	bgh = b + G - 0.5;
	cgh = c + G - 0.5;
	res = lanczosSumExpGScaled( a ) * lanczosSumExpGScaled( b ) /
		lanczosSumExpGScaled( c );
	ambh = a - 0.5 - b;
	if ( ( abs( b * ambh ) < ( cgh * 100.0 ) ) && a > 100.0 ) {
		// Special case where the base of the power term is close to 1; compute (1+x)^y instead:
		res *= exp( ambh * log1p( -b / cgh ) );
	} else {
		res *= pow( agh / cgh, a - 0.5 - b );
	}
	if ( cgh > 1e10 ) {
		// This avoids possible overflow, but appears to be marginally less accurate:
		res *= pow( (agh / cgh) * (bgh / cgh), b );
	} else {
		res *= pow( (agh * bgh) / (cgh * cgh), b );
	}
	res *= sqrt( E / bgh);
	// If a and b were originally less than 1 we need to scale the result:
	res *= prefix;
	return res;
} // end FUNCTION beta()

// EXPORTS //

module.exports = beta;
<commit_msg>Add parentheses<commit_after>'use strict';

/*
* The original C++ code and copyright notice is from the [Boost library]{http://www.boost.org/doc/libs/1_64_0/boost/math/special_functions/beta.hpp}.
*
* The implementation has been modified for JavaScript.
*/

/*
* (C) Copyright John Maddock 2006.
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var evalrational = require( '@stdlib/math/base/tools/evalrational' ).factory;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var pow = require( '@stdlib/math/base/special/pow' );
var E = require( '@stdlib/math/constants/float64-e' );
var EPSILON = require( '@stdlib/math/constants/float64-eps' );

// VARIABLES //

var G = 10.90051099999999983936049829935654997826;
var NUM = [
	709811.662581657956893540610814842699825,
	679979.847415722640161734319823103390728,
	293136.785721159725251629480984140341656,
	74887.5403291467179935942448101441897121,
	12555.29058241386295096255111537516768137,
	1443.42992444170669746078056942194198252,
	115.2419459613734722083208906727972935065,
	6.30923920573262762719523981992008976989,
	0.2266840463022436475495508977579735223818,
	0.004826466289237661857584712046231435101741,
	0.4624429436045378766270459638520555557321e-4
];
var DENOM = [
	0,
	362880,
	1026576,
	1172700,
	723680,
	269325,
	63273,
	9450,
	870,
	45,
	1
];

// FUNCTIONS //

/**
* Calculate the Lanczos approximation scaled by exp(G).
*
* @private
* @param {number} z - input value
* @returns {number} Lanczos approximation
*/
var lanczosSumExpGScaled = evalrational( NUM, DENOM );

// MAIN //

/**
* Evaluate the beta function.
*
* @param {NonNegativeNumber} a - input value
* @param {NonNegativeNumber} b - input value
* @returns {number} evaluated beta function
*
* @example
* var v = beta( 0, 0 );
* // returns Number.POSITIVE_INFINITY
*
* @example
* var v = beta( 1, 1 );
* // returns 1
*
* @example
* var v = beta( -1, 2 );
* // returns NaN
*
* @example
* var v = beta( 5, 0.2 );
* // returns ~3.382
*
* @example
* var v = beta( 4, 1 );
* // returns 0.25
*
* @example
* var v = beta( NaN, 2 );
* // returns NaN
*/
function beta( a, b ) {
	var prefix;
	var ambh;
	var agh;
	var bgh;
	var cgh;
	var res;
	var tmp;
	var c;

	prefix = 1;
	c = a + b;
	if ( isnan( a ) || isnan( b ) ) {
		return NaN;
	}
	if ( a < 0.0 || b < 0.0 ) {
		return NaN;
	}
	if ( b === 1.0 ) {
		return 1.0 / a;
	} else if ( a === 1.0 ) {
		return 1.0 / b;
	} else if ( c < EPSILON ) {
		res = c / a;
		res /= b;
		return res;
	}

	// Special cases:
	if ( c === a && b < EPSILON ) {
		return 1.0 / b;
	} else if ( c === b && a < EPSILON ) {
		return 1.0 / a;
	}

	if ( a < b ) {
		// Swap a and b:
		tmp = b;
		b = a;
		a = tmp;
	}

	// Lanczos calculation:
	agh = a + G - 0.5;
	bgh = b + G - 0.5;
	cgh = c + G - 0.5;
	res = lanczosSumExpGScaled( a ) * ( lanczosSumExpGScaled( b ) /
		lanczosSumExpGScaled( c ) );
	ambh = a - 0.5 - b;
	if ( ( abs( b * ambh ) < ( cgh * 100.0 ) ) && a > 100.0 ) {
		// Special case where the base of the power term is close to 1; compute (1+x)^y instead:
		res *= exp( ambh * log1p( -b / cgh ) );
	} else {
		res *= pow( agh / cgh, a - 0.5 - b );
	}
	if ( cgh > 1e10 ) {
		// This avoids possible overflow, but appears to be marginally less accurate:
		res *= pow( (agh / cgh) * (bgh / cgh), b );
	} else {
		res *= pow( (agh * bgh) / (cgh * cgh), b );
	}
	res *= sqrt( E / bgh);
	// If a and b were originally less than 1 we need to scale the result:
	res *= prefix;
	return res;
} // end FUNCTION beta()

// EXPORTS //

module.exports = beta;
<|endoftext|>


<commit_before>
// Facilitate testing/writing the HTML without the server
if (typeof io == 'undefined') {
  function io() {
    return {on:function(){}};
  }
}

var socket = io();

var channel = 144
var volume = 50;
var offsets = [
  {note: -36, pos: 0},
  {note: -12, pos: 27},
  {note: 0, pos: 40.5},
  {note: 24, pos: 67.25}
];
var offsetIndex = 1;
var pianoWidth = 1530 + 50;

// Dynamically scale the keyboard to fit any screen
$(window).bind('resize', dynamicResize);
function dynamicResize() {
  var w = $(window).width();
  var $p = $('#piano');

  if (w < pianoWidth) {
    var scale = w / pianoWidth;
    $p.css('transform', 'scale(' + scale + ')');
    $p.css('-webkit-transform', 'scale(' + scale + ')');
  }
}
// Initial Run on document ready
$(function(){
  dynamicResize();
});

// Populate and bind instrument/voice selection
var $instSelect = $('#instrument');
$(cvp75Instruments).each(function(index, instrument){
  $instSelect.append(
    $('<option>')
      .val(index)
      .text(instrument.name)
  );
});

$instSelect.change(function(e) {
  setTimeout(function () {
    $('#instrument_chzn').removeClass('chzn-container-active');
    $('.chzn-search input').blur();
    $("#piano").focus();
  }, 100);

  midi.instrument($(this).val());
}).chosen();

// Bind Select octave
$('#full-piano-wrap').bind('click', function(e){
  var pos = e.pageX - $(this).offset().left;
  offsetIndex = parseInt(pos / ($(this).width() / offsets.length));
  $('#full-select').css('left', offsets[offsetIndex].pos + '%')
});

// Bind piano key click
$('.key').bind('mousedown mouseup', function(e){
  var note = pianoKeys[this.id].note;
  midi.note(note + offsets[offsetIndex].note, (e.type == 'mousedown' ? volume : 0));
});

// Toggle options
$("#toggleKeyNames").click(function () {
  $("#piano div.kbkeyname").hide();
  $("#toggleKeyboardKeysNames").removeClass('on');
  $("#piano div.keyname").toggle();
  $(this).toggleClass('on');
 });

$("#toggleKeyboardKeysNames").click(function () {
  $("#piano div.keyname").hide();
  $("#toggleKeyNames").removeClass('on');
  $("#piano div.kbkeyname").toggle();
  $(this).toggleClass('on');
 });

// Move trough all the keys
$.each(pianoKeys, function(keyID, key) {
    // Bind Key presses
    $(document).bind('keyup keydown', key.bind, function (e){
      var $elem = $('#' + keyID);
      var down = (e.type == 'keydown');

      // Avoid repeat trigger
      if (down) {
        if (!$elem.is('.pressed')) {
          $elem.trigger('mousedown');
        } else {
          return false; // Leave early on repeat
        }
      } else {
        $elem.trigger('mouseup');
      }

      $elem.toggleClass('pressed', down);

      return false;
    });
});

socket.on('midiin', function (data) {
  // If this is a piano key press...
  if (data[0] == 144) {
    var isPressed = (data[2] != 0);
    var key = parseInt(data[1] - offsets[offsetIndex].note);

    // Is the Key within the visible range?
    if (key > 56 && key < 85) {
      for(var id in pianoKeys) {
        if (key == pianoKeys[id].note) {
          $('#' + id).toggleClass('pressed', isPressed);
          return false;
        }
      }
    }

  }

});

var midi = {
  note: function(note, volume) {
    var data  = [channel, parseInt(note), parseInt((volume ? volume : 0))];
    console.log('Sending:', data);

    socket.emit('midiout', data);
  },
  instrument: function(inst) {
    var data  = [192, parseInt(inst)];
    console.log('Sending:', data);

    socket.emit('midiout', data);
  }
}
<commit_msg>Fix global parsing bug from Chrome<commit_after>
// Facilitate testing/writing the HTML without the server
if (typeof io == 'undefined') {
  io = function() {
    return {on:function(){}};
  }
}

var socket = io();

var channel = 144
var volume = 50;
var offsets = [
  {note: -36, pos: 0},
  {note: -12, pos: 27},
  {note: 0, pos: 40.5},
  {note: 24, pos: 67.25}
];
var offsetIndex = 1;
var pianoWidth = 1530 + 50;

// Dynamically scale the keyboard to fit any screen
$(window).bind('resize', dynamicResize);
function dynamicResize() {
  var w = $(window).width();
  var $p = $('#piano');

  if (w < pianoWidth) {
    var scale = w / pianoWidth;
    $p.css('transform', 'scale(' + scale + ')');
    $p.css('-webkit-transform', 'scale(' + scale + ')');
  }
}
// Initial Run on document ready
$(function(){
  dynamicResize();
});

// Populate and bind instrument/voice selection
var $instSelect = $('#instrument');
$(cvp75Instruments).each(function(index, instrument){
  $instSelect.append(
    $('<option>')
      .val(index)
      .text(instrument.name)
  );
});

$instSelect.change(function(e) {
  setTimeout(function () {
    $('#instrument_chzn').removeClass('chzn-container-active');
    $('.chzn-search input').blur();
    $("#piano").focus();
  }, 100);

  midi.instrument($(this).val());
}).chosen();

// Bind Select octave
$('#full-piano-wrap').bind('click', function(e){
  var pos = e.pageX - $(this).offset().left;
  offsetIndex = parseInt(pos / ($(this).width() / offsets.length));
  $('#full-select').css('left', offsets[offsetIndex].pos + '%')
});

// Bind piano key click
$('.key').bind('mousedown mouseup', function(e){
  var note = pianoKeys[this.id].note;
  midi.note(note + offsets[offsetIndex].note, (e.type == 'mousedown' ? volume : 0));
});

// Toggle options
$("#toggleKeyNames").click(function () {
  $("#piano div.kbkeyname").hide();
  $("#toggleKeyboardKeysNames").removeClass('on');
  $("#piano div.keyname").toggle();
  $(this).toggleClass('on');
 });

$("#toggleKeyboardKeysNames").click(function () {
  $("#piano div.keyname").hide();
  $("#toggleKeyNames").removeClass('on');
  $("#piano div.kbkeyname").toggle();
  $(this).toggleClass('on');
 });

// Move trough all the keys
$.each(pianoKeys, function(keyID, key) {
    // Bind Key presses
    $(document).bind('keyup keydown', key.bind, function (e){
      var $elem = $('#' + keyID);
      var down = (e.type == 'keydown');

      // Avoid repeat trigger
      if (down) {
        if (!$elem.is('.pressed')) {
          $elem.trigger('mousedown');
        } else {
          return false; // Leave early on repeat
        }
      } else {
        $elem.trigger('mouseup');
      }

      $elem.toggleClass('pressed', down);

      return false;
    });
});

socket.on('midiin', function (data) {
  // If this is a piano key press...
  if (data[0] == 144) {
    var isPressed = (data[2] != 0);
    var key = parseInt(data[1] - offsets[offsetIndex].note);

    // Is the Key within the visible range?
    if (key > 56 && key < 85) {
      for(var id in pianoKeys) {
        if (key == pianoKeys[id].note) {
          $('#' + id).toggleClass('pressed', isPressed);
          return false;
        }
      }
    }

  }

});

var midi = {
  note: function(note, volume) {
    var data  = [channel, parseInt(note), parseInt((volume ? volume : 0))];
    console.log('Sending:', data);

    socket.emit('midiout', data);
  },
  instrument: function(inst) {
    var data  = [192, parseInt(inst)];
    console.log('Sending:', data);

    socket.emit('midiout', data);
  }
}
<|endoftext|>


<commit_before>var elements = {};

elements.sky = function () {
	return new THREE.Mesh(
		new THREE.SphereGeometry(1000, 60, 40),
		new THREE.MeshBasicMaterial({
			map: THREE.ImageUtils.loadTexture('resources/space.jpg', null, function () {
				scene.renderCamera();
			})
		})
	);
}

/*elements.ground = function () {
	return new THREE.Mesh(
		new THREE.CubeGeometry( GROUND_WIDTH, 6, GROUND_HEIGHT ),
		new THREE.MeshBasicMaterial({
			map: THREE.ImageUtils.loadTexture('resources/ground.jpg', null, function () {
				scene.renderCamera();
			})
		})
	);
}

*/
elements.goodMeteor = function () {
	return new THREE.Mesh(
		new THREE.SphereGeometry( 7, 30, 30 ),
		new THREE.MeshBasicMaterial ({
			color: 0xFFD700
		})
	);
}

elements.badMeteor = function () {
	return new THREE.Mesh(
		new THREE.SphereGeometry( Math.floor((Math.random()*7 )+4), 30, 30 ),
		new THREE.MeshBasicMaterial ({
			color: 0xFF0000
		})
	);

}

/*
for (var i = 0; i < 5; i++) {
	var meteorito = elements.goodMeteor();
	scene.addObject( meteorito )
	meteorito.position.x= Math.floor((Math.random()*-200 )+400);
	meteorito.position.y= Math.floor((Math.random()*200 ));
	meteorito.position.z= Math.floor((Math.random()*-200 )+400);

}

for (var i = 0; i < 10; i++) {
	var meteorito = elements.badMeteor();
	scene.addObject( meteorito )
	meteorito.position.x= Math.floor((Math.random()*-200 )+400);
	meteorito.position.y= Math.floor((Math.random()*200 ));
	meteorito.position.z= Math.floor((Math.random()*-200 )+400);

}
*/

elements.meteors = function( scene ) {
	for (var i = 0; i < 5; i++) {
		var meteorito = elements.goodMeteor();
		scene.addObject( meteorito )
		meteorito.position.x= Math.floor((Math.random()*-200 )+400);
		meteorito.position.y= Math.floor((Math.random()*200 ));
		meteorito.position.z= Math.floor((Math.random()*-200 )+400);
	}

	for (var i = 0; i < 10; i++) {
		var meteorito = elements.badMeteor();
		scene.addObject( meteorito )
		meteorito.position.x= Math.floor((Math.random()*-200 )+400);
		meteorito.position.y= Math.floor((Math.random()*200 ));
		meteorito.position.z= Math.floor((Math.random()*-200 )+400);
	}
}

elements.skateAlone = function () {
	return new THREE.Mesh(
		new THREE.CubeGeometry( 30, 2, 8 ),
		new THREE.MeshBasicMaterial({
			color: 0xEEEEEE
		})
	);
}

elements.skate = function (scene) {
	var self = {};
	var skate = elements.skateAlone();
	scene.addObject(skate);
	// Draw parts function
	self.move = function (positions) {
		skate.position.x = (positions.leftFoot[0]+positions.rightFoot[0])/2;
		skate.position.y = (positions.leftFoot[1]+positions.rightFoot[1])/2;
		skate.position.z = (positions.leftFoot[2]+positions.rightFoot[2])/2;
		skate.rotation.z = Math.atan(
			(positions.rightFoot[1]-positions.leftFoot[1])/
			(positions.rightFoot[0]-positions.leftFoot[0])
		);
	}
	return self;
}

elements.skeleton = function (scene) {
	var self = {};
	var parts = [
		'head', 'neck', 'leftShoulder', 'rightShoulder',
		'leftElbow', 'rightElbow','leftHand', 'rightHand',
		'torso', 'leftHip','rightHip', 'leftKnee', 'rightKnee',
		'leftFoot', 'rightFoot'
	];
	// Initializing parts
	parts.forEach(function (part) {
		self.parts[part] = new THREE.Mesh(
			new THREE.SphereGeometry( 2.5, 30, 30 ),
			new THREE.MeshBasicMaterial({
				color: 0xAAAAAA
			})
		);
		scene.addObject(self.parts[part]);
	})
	// Draw parts function
	self.move = function (positions) {
		Object.keys(positions).forEach( function(position) {
			if (!self.parts[position]) return;
			self.parts[position].position.x = positions[position][0];
			self.parts[position].position.y = positions[position][1];
			self.parts[position].position.z = positions[position][2];
		})
	}

	return self;
}<commit_msg>Meteors fixed<commit_after>var elements = {};

elements.sky = function () {
	return new THREE.Mesh(
		new THREE.SphereGeometry(1000, 60, 40),
		new THREE.MeshBasicMaterial({
			map: THREE.ImageUtils.loadTexture('resources/space.jpg', null, function () {
				scene.renderCamera();
			})
		})
	);
}

/*elements.ground = function () {
	return new THREE.Mesh(
		new THREE.CubeGeometry( GROUND_WIDTH, 6, GROUND_HEIGHT ),
		new THREE.MeshBasicMaterial({
			map: THREE.ImageUtils.loadTexture('resources/ground.jpg', null, function () {
				scene.renderCamera();
			})
		})
	);
}

*/
elements.goodMeteor = function () {
	return new THREE.Mesh(
		new THREE.SphereGeometry( 7, 30, 30 ),
		new THREE.MeshBasicMaterial ({
			color: 0xFFD700
		})
	);
}

elements.badMeteor = function () {
	return new THREE.Mesh(
		new THREE.SphereGeometry( Math.floor((Math.random()*7 )+4), 30, 30 ),
		new THREE.MeshBasicMaterial ({
			color: 0xFF0000
		})
	);

}

elements.skateAlone = function () {
	return new THREE.Mesh(
		new THREE.CubeGeometry( 30, 2, 8 ),
		new THREE.MeshBasicMaterial({
			color: 0xEEEEEE
		})
	);
}

elements.skate = function (scene) {
	var self = {};
	var skate = elements.skateAlone();
	scene.addObject(skate);
	// Draw parts function
	self.move = function (positions) {
		skate.position.x = (positions.leftFoot[0]+positions.rightFoot[0])/2;
		skate.position.y = (positions.leftFoot[1]+positions.rightFoot[1])/2;
		skate.position.z = (positions.leftFoot[2]+positions.rightFoot[2])/2;
		skate.rotation.z = Math.atan(
			(positions.rightFoot[1]-positions.leftFoot[1])/
			(positions.rightFoot[0]-positions.leftFoot[0])
		);
	}
	return self;
}

elements.skeleton = function (scene) {
	var self = {};
	var parts = [
		'head', 'neck', 'leftShoulder', 'rightShoulder',
		'leftElbow', 'rightElbow','leftHand', 'rightHand',
		'torso', 'leftHip','rightHip', 'leftKnee', 'rightKnee',
		'leftFoot', 'rightFoot'
	];
	// Initializing parts
	parts.forEach(function (part) {
		self.parts[part] = new THREE.Mesh(
			new THREE.SphereGeometry( 2.5, 30, 30 ),
			new THREE.MeshBasicMaterial({
				color: 0xAAAAAA
			})
		);
		scene.addObject(self.parts[part]);
	})
	// Draw parts function
	self.move = function (positions) {
		Object.keys(positions).forEach( function(position) {
			if (!self.parts[position]) return;
			self.parts[position].position.x = positions[position][0];
			self.parts[position].position.y = positions[position][1];
			self.parts[position].position.z = positions[position][2];
		})
	}

	return self;
}<|endoftext|>


<commit_before><commit_msg>dirty hack to fix karma tests (exclude axios.js)<commit_after><|endoftext|>


<commit_before>import { useState } from 'react';

const useModal = (initialState = false) => {
    const [isOpen, setModalState] = useState(initialState);
    const open = () => setModalState(true);
    const close = () => setModalState(false);
    const toggle = () => setModalState(!isOpen);

    return {
        isOpen,
        open,
        toggle,
        close
    };
};

export default useModal;<commit_msg>Fix #96 - Remove useModal.js<commit_after><|endoftext|>


<commit_before>/**
 * @file Require implementation
 * @since 0.2.2
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfArrayForEach*/ // Almost like [].forEach (undefined are also enumerated)
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*global _gpfPathJoin*/ // Join all arguments together and normalize the resulting path
/*global _gpfPromisify*/ // Converts any value into a Promise
/*global _gpfRequireLoad*/ // Load the resource
/*exported _gpfRequireAllocate*/ // Allocate a new require context with the proper methods
/*#endif*/

/* this is globally used as the current context in this module */
/*jshint -W040*/
/*eslint-disable no-invalid-this*/

_gpfErrorDeclare("require", {

    /**
     * ### Summary
     *
     * Invalid {@link gpf.require.configure} option
     *
     * ### Description
     *
     * This error is triggered whenever an option passed to {@link gpf.require.configure} is not recognized.
     * Please check the {@link gpf.typedef.requireOptions} documentation.
     * @since 0.2.2
     */
    invalidRequireConfigureOption:
        "Invalid configuration option"
});

/**
 * @namespace gpf.require
 * @description Root namespace for the GPF modularization helpers.
 * @since 0.2.2
 */

/**
 * @typedef gpf.typedef.requireOptions
 * @property {String} [base] Base path used to resolve names
 * @property {Object} [cache] Inject names into the require cache
 * @property {Boolean} [clearCache=false] When set, the require cache is cleared
 * @since 0.2.2
 */

/**
 * @typedef gpf.typedef._requireContext
 * @property {String} base Base path used to resolve names
 * @property {Object} cache Dictionary of loaded requires
 * @since 0.2.2
 */

/**
 * Valuate the option priority to have them executed in the proper order
 *
 * @param {String} name option name
 * @return {Number} Option priority
 * @since 0.2.2
 */
function _gpfRequireOptionPriority (name) {
    if ("clearCache" === name) {
        return -1;
    }
    return 1;
}

/**
 *  Dictionary of option name to function handling the option
 * @type {Object}
 * @since 0.2.2
 */
var _gpfRequireOptionHandler = {

    base: function (base) {
        this.base = base;
    },

    cache: function (cache) {
        _gpfArrayForEach(Object.keys(cache), function (name) {
            this.cache[name] = _gpfPromisify(cache[name]);
        }, this);
    },

    clearCache: function () {
        this.cache = {};
    }

};

/**
 * Configure the {@link gpf.require} layer
 *
 * @param {gpf.typedef.requireOptions} options Options to configure
 * @since 0.2.2
 */
function _gpfRequireConfigure (options) {
    var me = this;
    _gpfArrayForEach(Object.keys(options).sort(function (key1, key2) {
        // Some keys must be processed first
        return _gpfRequireOptionPriority(key1) - _gpfRequireOptionPriority(key2);
    }), function (key) {
        (_gpfRequireOptionHandler[key] || gpf.error.invalidRequireConfigureOption).call(me, options[key]);
    }, me);
}

/**
 * Resolves the resource name according to current require context
 *
 * @param {String} name Relative resource name
 * @return {String} Resolved name
 * @since 0.2.2
 */
function _gpfRequireResolve (name) {
    return _gpfPathJoin(this.base, name);
}

/**
 * Get the cached resource or load it
 *
 * @param {String} name Resource name
 * @return {Promise<*>} Resource association
 * @since 0.2.2
 */
function _gpfRequireGet (name) {
    var me = this,
        promise;
    if (me.cache[name]) {
        return me.cache[name];
    }
    promise = _gpfRequireLoad.call(me, name);
    me.cache[name] = promise;
    return promise;
}

/**
 * Modularization helper.
 * Defines a new module by executing the factory function with the loaded dependencies.
 *
 * @param {Object} dependencies Dictionary of dependencies, the keys are preserved while passing the result
 * dictionary to the factory function
 * @param {Function|*} factory Can be either:
 * * A factory function executed when all dependencies are resolved, the first parameter will be a dictionary
 *   with all dependencies indexed by their name (as initially specified in the dependencies parameter).
 *   The result of the factory function will be cached as the result of this resource
 * * Any value that will be cached as well as the result of this resource
 * @return {Promise<*>} Resolved with the factory function result or the object
 * @since 0.2.2
 */
function _gpfRequireDefine (dependencies, factory) {
    var me = this,
        promises = [],
        keys = Object.keys(dependencies);
    _gpfArrayForEach(keys, function (key) {
        promises.push(_gpfRequireGet.call(me, _gpfRequireResolve.call(me, dependencies[key])));
    }, me);
    return Promise.all(promises)
        .then(function (resources) {
            var result,
                require;
            if ("function" === typeof factory) {
                require = {};
                _gpfArrayForEach(keys, function (key, index) {
                    require[key] = resources[index];
                });
                result = factory(require);
            } else {
                result = factory;
            }
            return result;
        });
}

/**
 * Allocate a new require context with the proper methods
 *
 * @param {Object} parentContext Context to inherit from
 * @param {gpf.typedef.requireOptions} [options] Options to configure
 * @return {Object} Containing {@link gpf.require.define}, {@link gpf.require.resolve} and {@link gpf.require.configure}
 * @since 0.2.2
 */
function _gpfRequireAllocate (parentContext, options) {
    var context = Object.create(parentContext), // cache content is shared but other properties are protected
        require = {};
    require.define = _gpfRequireDefine.bind(context);
    require.resolve = _gpfRequireResolve.bind(context);
    require.configure = _gpfRequireConfigure.bind(context);
    if (options) {
        require.configure(options);
    }
    return require;
}

gpf.require = _gpfRequireAllocate({
    base: "",
    cache: {}
});

/**
 * @method gpf.require.define
 * @gpf:sameas _gpfRequireDefine
 * @since 0.2.2
 */

/**
 * @method gpf.require.configure
 * @gpf:sameas _gpfRequireConfigure
 * @since 0.2.2
 */

/**
 * @method gpf.require.resolve
 * @gpf:sameas _gpfRequireResolve
 * @since 0.2.2
 */
<commit_msg>Fixing error (#168)<commit_after>/**
 * @file Require implementation
 * @since 0.2.2
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfArrayForEach*/ // Almost like [].forEach (undefined are also enumerated)
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*global _gpfPathJoin*/ // Join all arguments together and normalize the resulting path
/*global _gpfPromisify*/ // Converts any value into a Promise
/*global _gpfRequireLoad*/ // Load the resource
/*exported _gpfRequireAllocate*/ // Allocate a new require context with the proper methods
/*#endif*/

/* this is globally used as the current context in this module */
/*jshint -W040*/
/*eslint-disable no-invalid-this*/

_gpfErrorDeclare("require", {

    /**
     * ### Summary
     *
     * Invalid {@link gpf.require.configure} option
     *
     * ### Description
     *
     * This error is triggered whenever an option passed to {@link gpf.require.configure} is not recognized.
     * Please check the {@link gpf.typedef.requireOptions} documentation.
     * @since 0.2.2
     */
    invalidRequireConfigureOption:
        "Invalid configuration option"
});

/**
 * @namespace gpf.require
 * @description Root namespace for the GPF modularization helpers.
 * @since 0.2.2
 */

/**
 * @typedef gpf.typedef.requireOptions
 * @property {String} [base] Base path used to resolve names
 * @property {Object} [cache] Inject names into the require cache
 * @property {Boolean} [clearCache=false] When set, the require cache is cleared
 * @since 0.2.2
 */

/**
 * @typedef gpf.typedef._requireContext
 * @property {String} base Base path used to resolve names
 * @property {Object} cache Dictionary of loaded requires
 * @since 0.2.2
 */

/**
 * Valuate the option priority to have them executed in the proper order
 *
 * @param {String} name option name
 * @return {Number} Option priority
 * @since 0.2.2
 */
function _gpfRequireOptionPriority (name) {
    if ("clearCache" === name) {
        return -1;
    }
    return 1;
}

/**
 *  Dictionary of option name to function handling the option
 * @type {Object}
 * @since 0.2.2
 */
var _gpfRequireOptionHandler = {

    base: function (base) {
        this.base = base;
    },

    cache: function (cache) {
        _gpfArrayForEach(Object.keys(cache), function (name) {
            this.cache[name] = _gpfPromisify(cache[name]);
        }, this);
    },

    clearCache: function () {
        this.cache = {};
    }

};

/**
 * Configure the {@link gpf.require} layer
 *
 * @param {gpf.typedef.requireOptions} options Options to configure
 * @since 0.2.2
 */
function _gpfRequireConfigure (options) {
    var me = this;
    _gpfArrayForEach(Object.keys(options).sort(function (key1, key2) {
        // Some keys must be processed first
        return _gpfRequireOptionPriority(key1) - _gpfRequireOptionPriority(key2);
    }), function (key) {
        (_gpfRequireOptionHandler[key] || gpf.Error.invalidRequireConfigureOption).call(me, options[key]);
    }, me);
}

/**
 * Resolves the resource name according to current require context
 *
 * @param {String} name Relative resource name
 * @return {String} Resolved name
 * @since 0.2.2
 */
function _gpfRequireResolve (name) {
    return _gpfPathJoin(this.base, name);
}

/**
 * Get the cached resource or load it
 *
 * @param {String} name Resource name
 * @return {Promise<*>} Resource association
 * @since 0.2.2
 */
function _gpfRequireGet (name) {
    var me = this,
        promise;
    if (me.cache[name]) {
        return me.cache[name];
    }
    promise = _gpfRequireLoad.call(me, name);
    me.cache[name] = promise;
    return promise;
}

/**
 * Modularization helper.
 * Defines a new module by executing the factory function with the loaded dependencies.
 *
 * @param {Object} dependencies Dictionary of dependencies, the keys are preserved while passing the result
 * dictionary to the factory function
 * @param {Function|*} factory Can be either:
 * * A factory function executed when all dependencies are resolved, the first parameter will be a dictionary
 *   with all dependencies indexed by their name (as initially specified in the dependencies parameter).
 *   The result of the factory function will be cached as the result of this resource
 * * Any value that will be cached as well as the result of this resource
 * @return {Promise<*>} Resolved with the factory function result or the object
 * @since 0.2.2
 */
function _gpfRequireDefine (dependencies, factory) {
    var me = this,
        promises = [],
        keys = Object.keys(dependencies);
    _gpfArrayForEach(keys, function (key) {
        promises.push(_gpfRequireGet.call(me, _gpfRequireResolve.call(me, dependencies[key])));
    }, me);
    return Promise.all(promises)
        .then(function (resources) {
            var result,
                require;
            if ("function" === typeof factory) {
                require = {};
                _gpfArrayForEach(keys, function (key, index) {
                    require[key] = resources[index];
                });
                result = factory(require);
            } else {
                result = factory;
            }
            return result;
        });
}

/**
 * Allocate a new require context with the proper methods
 *
 * @param {Object} parentContext Context to inherit from
 * @param {gpf.typedef.requireOptions} [options] Options to configure
 * @return {Object} Containing {@link gpf.require.define}, {@link gpf.require.resolve} and {@link gpf.require.configure}
 * @since 0.2.2
 */
function _gpfRequireAllocate (parentContext, options) {
    var context = Object.create(parentContext), // cache content is shared but other properties are protected
        require = {};
    require.define = _gpfRequireDefine.bind(context);
    require.resolve = _gpfRequireResolve.bind(context);
    require.configure = _gpfRequireConfigure.bind(context);
    if (options) {
        require.configure(options);
    }
    return require;
}

gpf.require = _gpfRequireAllocate({
    base: "",
    cache: {}
});

/**
 * @method gpf.require.define
 * @gpf:sameas _gpfRequireDefine
 * @since 0.2.2
 */

/**
 * @method gpf.require.configure
 * @gpf:sameas _gpfRequireConfigure
 * @since 0.2.2
 */

/**
 * @method gpf.require.resolve
 * @gpf:sameas _gpfRequireResolve
 * @since 0.2.2
 */
<|endoftext|>