<commit_before>
var CustomGraph = (args) => {
  var graph = Viva.Graph.graph()
  var graphics = Viva.Graph.View.svgGraphics()

  // color scheme
  var colors = {
    root: '#086788',
    node: '#06AED5',
    active: '#DD1C1A',
    hover: '#F0C808',
    from: '#DD1C1A',
    to: '#06AED5'
  }

  var events = {
    // on hover over node
    over: (e) => {
      e.target.attr('fill', colors.hover)
      // highlightRelatedLinks(node.id, true)
    },
    // on hover out of node
    out: (e) => {
      var color
      if (e.target.attr('active') === 'true') {
        color = colors.active
      }
      else if (e.target.attr('type') === 'root') {
        color = colors.root
      }
      else if (e.target.attr('type') === 'node') {
        color = colors.node
      }
      e.target.attr('fill', color)
      // highlightRelatedLinks(node.id, false)
    },
    // on click node
    click: (e) => {
      // reset nodes
      document.querySelectorAll('circle').forEach((node) => {
        var color = node.attr('type') === 'root'
          ? colors.root : colors.node
        node.attr('fill', color).attr('active', false)
      })

      // reset links
      document.querySelectorAll('path').forEach((link) => {
        link.attr('stroke', 'gray')
      })

      // set active node
      e.target
        .attr('fill', colors.active)
        .attr('active', true)

      // highlightRelatedLinks(node.id, true)
    },
  }

  // executed every time a new node or link is added to the graph
  var custom = {
    node: () => {
      graphics
        .node((node) => {
          // SVG group of elements: http://www.w3.org/TR/SVG/struct.html
          var group = Viva.Graph.svg('g')

          var text = Viva.Graph.svg('text')
            .attr('y', '-10px')
            .attr('style', 'display: ' + (args.showNames ? 'block' : 'none'))
            .text(node.id)
          group.append(text)

          var elem
          if (node.data.type === 'root') {
            elem = Viva.Graph.svg('circle')
              .attr('r', 9)
              .attr('stroke-width', 0)
              .attr('fill', colors.root)
              .attr('gem', node.id)
              .attr('type', 'root')
              .attr('active', false)
          }
          else if (node.data.type === 'node') {
            elem = Viva.Graph.svg('circle')
              .attr('r', 7)
              .attr('stroke-width', 0)
              .attr('fill', colors.node)
              .attr('gem', node.id)
              .attr('type', 'node')
              .attr('active', false)
          }
          elem.addEventListener('click', events.click)
          elem.addEventListener('mouseover', events.over)
          elem.addEventListener('mouseout', events.out)
          group.append(elem)

          return group
        })
        .placeNode((nodeUI, pos) => {
          nodeUI.attr('transform',
            'translate(' + (pos.x - 0/2) + ',' + (pos.y - 0/2) + ')')
        })
    },
    link: () => {
      function createMarker (id) {
        return Viva.Graph.svg('marker')
          .attr('id', id)
          .attr('viewBox', '0 0 10 10')
          .attr('refX', '11')
          .attr('refY', '5')
          .attr('markerUnits', 'strokeWidth')
          .attr('markerWidth', '10')
          .attr('markerHeight', '5')
          .attr('orient', 'auto')
          .attr('stroke', 'gray')
          .attr('fill', '#333')
      }

      var marker = createMarker('Triangle')
      marker.append('path').attr('d', 'M 0 0 L 10 5 L 0 10 z')

      var defs = graphics.getSvgRoot().append('defs')
      defs.append(marker)

      var geom = Viva.Graph.geom()

      graphics
        .link((link) =>
          Viva.Graph.svg('path')
            .attr('stroke', 'gray')
            .attr('marker-end', 'url(#Triangle)')
        )
        .placeLink((linkUI, fromPos, toPos) => {
          var toNodeSize = 14
          var fromNodeSize = 14

          var from = geom.intersectRect(
            // rectangle:
            fromPos.x - fromNodeSize / 2 + 2, // left
            fromPos.y - fromNodeSize / 2 + 2, // top
            fromPos.x + fromNodeSize / 2 - 2, // right
            fromPos.y + fromNodeSize / 2 - 2, // bottom
            // segment:
            fromPos.x, fromPos.y, toPos.x, toPos.y)
              || fromPos // if no intersection found - return center of the node

          var to = geom.intersectRect(
            // rectangle:
            toPos.x - toNodeSize / 2 + 2, // left
            toPos.y - toNodeSize / 2 + 2, // top
            toPos.x + toNodeSize / 2 - 2, // right
            toPos.y + toNodeSize / 2 - 2, // bottom
            // segment:
            toPos.x, toPos.y, fromPos.x, fromPos.y)
              || toPos // if no intersection found - return center of the node

          var data = 'M' + from.x + ',' + from.y + 'L' + to.x + ',' + to.y

          linkUI.attr('d', data)
        })
    }
  }

  function highlightRelatedLinks (nodeId, isOn) {
    graph.forEachLinkedNode(nodeId, (node, link) => {
      if (link && link.ui) {
        if (link.fromId === nodeId) {
          link.ui.attr('stroke', isOn ? colors.from : 'gray')
        }
        else if (link.toId === nodeId) {
          link.ui.attr('stroke', isOn ? colors.to : 'gray')
        }
      }
    })
  }

  graph.run = () => {
    custom.node()

    var renderer = Viva.Graph.View.renderer(graph, {
      container: document.querySelector('#graph'),
      graphics: graphics
    })
    renderer.run()

    custom.link()
  }

  return graph
}
<commit_msg>Return back the title child element for the circle svg element<commit_after>
var CustomGraph = (args) => {
  var graph = Viva.Graph.graph()
  var graphics = Viva.Graph.View.svgGraphics()

  // color scheme
  var colors = {
    root: '#086788',
    node: '#06AED5',
    active: '#DD1C1A',
    hover: '#F0C808',
    from: '#DD1C1A',
    to: '#06AED5'
  }

  var events = {
    // on hover over node
    over: (e) => {
      e.target.attr('fill', colors.hover)
      // highlightRelatedLinks(node.id, true)
    },
    // on hover out of node
    out: (e) => {
      var color
      if (e.target.attr('active') === 'true') {
        color = colors.active
      }
      else if (e.target.attr('type') === 'root') {
        color = colors.root
      }
      else if (e.target.attr('type') === 'node') {
        color = colors.node
      }
      e.target.attr('fill', color)
      // highlightRelatedLinks(node.id, false)
    },
    // on click node
    click: (e) => {
      // reset nodes
      document.querySelectorAll('circle').forEach((node) => {
        var color = node.attr('type') === 'root'
          ? colors.root : colors.node
        node.attr('fill', color).attr('active', false)
      })

      // reset links
      document.querySelectorAll('path').forEach((link) => {
        link.attr('stroke', 'gray')
      })

      // set active node
      e.target
        .attr('fill', colors.active)
        .attr('active', true)

      // highlightRelatedLinks(node.id, true)
    },
  }

  // executed every time a new node or link is added to the graph
  var custom = {
    node: () => {
      graphics
        .node((node) => {
          // SVG group of elements: http://www.w3.org/TR/SVG/struct.html
          var group = Viva.Graph.svg('g')

          var text = Viva.Graph.svg('text')
            .attr('y', '-10px')
            .attr('style', 'display: ' + (args.showNames ? 'block' : 'none'))
            .text(node.id)
          group.append(text)

          var elem
          if (node.data.type === 'root') {
            elem = Viva.Graph.svg('circle')
              .attr('r', 9)
              .attr('stroke-width', 0)
              .attr('fill', colors.root)
              .attr('gem', node.id)
              .attr('type', 'root')
              .attr('active', false)
          }
          else if (node.data.type === 'node') {
            elem = Viva.Graph.svg('circle')
              .attr('r', 7)
              .attr('stroke-width', 0)
              .attr('fill', colors.node)
              .attr('gem', node.id)
              .attr('type', 'node')
              .attr('active', false)
          }
          elem.append('title').text(node.id)
          elem.addEventListener('click', events.click)
          elem.addEventListener('mouseover', events.over)
          elem.addEventListener('mouseout', events.out)
          group.append(elem)

          return group
        })
        .placeNode((nodeUI, pos) => {
          nodeUI.attr('transform',
            'translate(' + (pos.x - 0/2) + ',' + (pos.y - 0/2) + ')')
        })
    },
    link: () => {
      function createMarker (id) {
        return Viva.Graph.svg('marker')
          .attr('id', id)
          .attr('viewBox', '0 0 10 10')
          .attr('refX', '11')
          .attr('refY', '5')
          .attr('markerUnits', 'strokeWidth')
          .attr('markerWidth', '10')
          .attr('markerHeight', '5')
          .attr('orient', 'auto')
          .attr('stroke', 'gray')
          .attr('fill', '#333')
      }

      var marker = createMarker('Triangle')
      marker.append('path').attr('d', 'M 0 0 L 10 5 L 0 10 z')

      var defs = graphics.getSvgRoot().append('defs')
      defs.append(marker)

      var geom = Viva.Graph.geom()

      graphics
        .link((link) =>
          Viva.Graph.svg('path')
            .attr('stroke', 'gray')
            .attr('marker-end', 'url(#Triangle)')
        )
        .placeLink((linkUI, fromPos, toPos) => {
          var toNodeSize = 14
          var fromNodeSize = 14

          var from = geom.intersectRect(
            // rectangle:
            fromPos.x - fromNodeSize / 2 + 2, // left
            fromPos.y - fromNodeSize / 2 + 2, // top
            fromPos.x + fromNodeSize / 2 - 2, // right
            fromPos.y + fromNodeSize / 2 - 2, // bottom
            // segment:
            fromPos.x, fromPos.y, toPos.x, toPos.y)
              || fromPos // if no intersection found - return center of the node

          var to = geom.intersectRect(
            // rectangle:
            toPos.x - toNodeSize / 2 + 2, // left
            toPos.y - toNodeSize / 2 + 2, // top
            toPos.x + toNodeSize / 2 - 2, // right
            toPos.y + toNodeSize / 2 - 2, // bottom
            // segment:
            toPos.x, toPos.y, fromPos.x, fromPos.y)
              || toPos // if no intersection found - return center of the node

          var data = 'M' + from.x + ',' + from.y + 'L' + to.x + ',' + to.y

          linkUI.attr('d', data)
        })
    }
  }

  function highlightRelatedLinks (nodeId, isOn) {
    graph.forEachLinkedNode(nodeId, (node, link) => {
      if (link && link.ui) {
        if (link.fromId === nodeId) {
          link.ui.attr('stroke', isOn ? colors.from : 'gray')
        }
        else if (link.toId === nodeId) {
          link.ui.attr('stroke', isOn ? colors.to : 'gray')
        }
      }
    })
  }

  graph.run = () => {
    custom.node()

    var renderer = Viva.Graph.View.renderer(graph, {
      container: document.querySelector('#graph'),
      graphics: graphics
    })
    renderer.run()

    custom.link()
  }

  return graph
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Validate = exports;

function InvalidValueError(message) {
  this.message = message;
  this.name = 'InvalidValueError';
  Error.captureStackTrace(this, InvalidValueError);
}
InvalidValueError.prototype = Object.create(Error.prototype);
InvalidValueError.prototype.constructor = InvalidValueError;

InvalidValueError.prepend = function(message, error) {
  if (error instanceof InvalidValueError) {
    return new InvalidValueError(message + ': ' + error.message);
  }
  return error;
};

Validate.InvalidValueError = InvalidValueError;

Validate.acceptAll = function(value) {
  return value;
};

Validate.optional = function(validator) {
  return function(value) {
    return (value == undefined) ? value : validator(value);
  };
};

Validate.that = function(predicate, message) {
  return function(value) {
    if (predicate(value)) return value;
    throw new InvalidValueError(message);
  };
};

Validate.number = Validate.that(function(value) {
  return typeof value === 'number';
}, 'not a number');

Validate.string = Validate.that(function(value) {
  return typeof value === 'string';
}, 'not a string');

Validate.object = function(propertyValidators) {
  return function(object) {
    var result = {};

    if (!object || typeof object !== 'object') {
      throw new InvalidValueError('not an Object');
    }

    // Validate all properties.
    for (key in propertyValidators) {
      var validator = propertyValidators[key];
      try {
        var valid = validator(object[key]);
      } catch (error) {
        if (key in object) {
          throw InvalidValueError.prepend('in property "' + key + '"', error);
        } else {
          throw new InvalidValueError('missing property "' + key + '"');
        }
      }
      if (valid !== undefined) {
        result[key] = valid;
      }
    }

    // Check for unexpected properties.
    for (var key in object) {
      if (!propertyValidators[key]) {
        throw new InvalidValueError('unexpected property "' + key + '"');
      }
    }

    return result;
  };
};

Validate.array = function(validator) {
  return function(array) {
    var result = [];

    if (Object.prototype.toString.call(array) !== '[object Array]') {
      throw new InvalidValueError('not an Array');
    }

    for (var i = 0; i < array.length; ++i) {
      try {
        result[i] = validator(array[i]);
      } catch (error) {
        throw InvalidValueError.prepend('at index ' + i, error);
      }
    }

    return result;
  };
};

Validate.oneOf = function(names) {
  var myObject = {};
  var quotedNames = [];
  names.forEach(function(name) {
    myObject[name] = true;
    quotedNames.push('"' + name + '"');
  });

  return function(value) {
    if (myObject[value]) return value;
    throw new InvalidValueError('not one of ' + quotedNames.join(', '));
  };
};

Validate.atLeastOneOfProperties = function(names) {
  return function(value) {
    if (!value) return value;

    var quotedNames = [];
    for (var name of names) {
      if (name in value) {
        return value;
      }
      quotedNames.push('"' + name + '"');
    }

    throw new InvalidValueError(
        'one of ' + quotedNames.join(', ') + ' is required');
  };
};

Validate.mutuallyExclusiveProperties = function(names, oneRequired) {
  return function(value) {
    if (!value) return value;

    var present = [];
    var quotedNames = [];
    names.forEach(function(name) {
      if (name in value) {
        present.push('"' + name + '"');
      }
      quotedNames.push('"' + name + '"');
    });

    if (present.length > 1) {
      throw new InvalidValueError(
          'cannot specify properties '
          + present.slice(0, -1).join(', ')
          + ' and '
          + present.slice(-1)
          + ' together');
    } else if (present.length == 0 && oneRequired) {
      throw new InvalidValueError(
          'one of ' + quotedNames.join(', ') + ' is required');
    }

    return value;
  };
};

Validate.mutuallyExclusivePropertiesRequired = function(names) {
  return Validate.mutuallyExclusiveProperties(names, true);
};

Validate.compose = function(validators) {
  return function(value) {
    validators.forEach(function(validate) {
      value = validate(value);
    });
    return value;
  };
};

Validate.boolean = Validate.compose([
  Validate.that(function(value) {
    return typeof value === 'boolean';
  }, 'not a boolean'),
  function(value) {
    // In each API, boolean fields default to false, and the presence of
    // a querystring value indicates true, so we omit the value if
    // explicitly set to false.
    return value ? value : undefined;
  }
]);<commit_msg>Fix compatibility of atLeastOneOfProperties with older versions of node<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var Validate = exports;

function InvalidValueError(message) {
  this.message = message;
  this.name = 'InvalidValueError';
  Error.captureStackTrace(this, InvalidValueError);
}
InvalidValueError.prototype = Object.create(Error.prototype);
InvalidValueError.prototype.constructor = InvalidValueError;

InvalidValueError.prepend = function(message, error) {
  if (error instanceof InvalidValueError) {
    return new InvalidValueError(message + ': ' + error.message);
  }
  return error;
};

Validate.InvalidValueError = InvalidValueError;

Validate.acceptAll = function(value) {
  return value;
};

Validate.optional = function(validator) {
  return function(value) {
    return (value == undefined) ? value : validator(value);
  };
};

Validate.that = function(predicate, message) {
  return function(value) {
    if (predicate(value)) return value;
    throw new InvalidValueError(message);
  };
};

Validate.number = Validate.that(function(value) {
  return typeof value === 'number';
}, 'not a number');

Validate.string = Validate.that(function(value) {
  return typeof value === 'string';
}, 'not a string');

Validate.object = function(propertyValidators) {
  return function(object) {
    var result = {};

    if (!object || typeof object !== 'object') {
      throw new InvalidValueError('not an Object');
    }

    // Validate all properties.
    for (key in propertyValidators) {
      var validator = propertyValidators[key];
      try {
        var valid = validator(object[key]);
      } catch (error) {
        if (key in object) {
          throw InvalidValueError.prepend('in property "' + key + '"', error);
        } else {
          throw new InvalidValueError('missing property "' + key + '"');
        }
      }
      if (valid !== undefined) {
        result[key] = valid;
      }
    }

    // Check for unexpected properties.
    for (var key in object) {
      if (!propertyValidators[key]) {
        throw new InvalidValueError('unexpected property "' + key + '"');
      }
    }

    return result;
  };
};

Validate.array = function(validator) {
  return function(array) {
    var result = [];

    if (Object.prototype.toString.call(array) !== '[object Array]') {
      throw new InvalidValueError('not an Array');
    }

    for (var i = 0; i < array.length; ++i) {
      try {
        result[i] = validator(array[i]);
      } catch (error) {
        throw InvalidValueError.prepend('at index ' + i, error);
      }
    }

    return result;
  };
};

Validate.oneOf = function(names) {
  var myObject = {};
  var quotedNames = [];
  names.forEach(function(name) {
    myObject[name] = true;
    quotedNames.push('"' + name + '"');
  });

  return function(value) {
    if (myObject[value]) return value;
    throw new InvalidValueError('not one of ' + quotedNames.join(', '));
  };
};

Validate.atLeastOneOfProperties = function(names) {
  return function(value) {
    if (!value) return value;

    var quotedNames = [];
    for (var i = 0; i < names.length; i++) {
      if (names[i] in value) {
        return value;
      }
      quotedNames.push('"' + names[i] + '"');
    }

    throw new InvalidValueError(
        'one of ' + quotedNames.join(', ') + ' is required');
  };
};

Validate.mutuallyExclusiveProperties = function(names, oneRequired) {
  return function(value) {
    if (!value) return value;

    var present = [];
    var quotedNames = [];
    names.forEach(function(name) {
      if (name in value) {
        present.push('"' + name + '"');
      }
      quotedNames.push('"' + name + '"');
    });

    if (present.length > 1) {
      throw new InvalidValueError(
          'cannot specify properties '
          + present.slice(0, -1).join(', ')
          + ' and '
          + present.slice(-1)
          + ' together');
    } else if (present.length == 0 && oneRequired) {
      throw new InvalidValueError(
          'one of ' + quotedNames.join(', ') + ' is required');
    }

    return value;
  };
};

Validate.mutuallyExclusivePropertiesRequired = function(names) {
  return Validate.mutuallyExclusiveProperties(names, true);
};

Validate.compose = function(validators) {
  return function(value) {
    validators.forEach(function(validate) {
      value = validate(value);
    });
    return value;
  };
};

Validate.boolean = Validate.compose([
  Validate.that(function(value) {
    return typeof value === 'boolean';
  }, 'not a boolean'),
  function(value) {
    // In each API, boolean fields default to false, and the presence of
    // a querystring value indicates true, so we omit the value if
    // explicitly set to false.
    return value ? value : undefined;
  }
]);<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Vanderbilt University, All rights reserved.
 *
 * Author: Zsolt Lattmann
 *
 * Server side BLOB client implementation.
 */

define(['blob/BlobClient', 'blob/BlobMetadata', 'http', 'https', 'util/StringStreamWriter'],
    function (BlobClient, BlobMetadata, http, https, StringStreamWriter) {

        /**
         * Initializes a new instance of a server side file system object.
         *
         * Note: This code strictly runs in node.js (server side).
         *
         * @param {{}} parameters
         * @constructor
         */
        function BlobServerClient(parameters) {
            BlobClient.call(this);
            this.serverPort = parameters.serverPort;
            this._clientSession = parameters.sessionId;
        }

        // Inherits from BlobClient
        BlobServerClient.prototype = Object.create(BlobClient.prototype);

        // Override the constructor with this object's constructor
        BlobServerClient.prototype.constructor = BlobServerClient;

        BlobServerClient.prototype.getMetadata = function (hash, callback) {
            var options = {
                hostname: '127.0.0.1',
                port: this.serverPort,
                path: this.getMetadataURL(hash),
                method: 'GET'
            };

            this._sendHttpRequest(options, function (err, data) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, JSON.parse(data));
            });
        };

        BlobServerClient.prototype.getObject = function (hash, callback) {
            var options = {
                hostname: '127.0.0.1',
                port: this.serverPort,
                path: this.getViewURL(hash),
                method: 'GET'
            };

            this._sendHttpRequest(options, function (err, data) {
                if (err) {
                    callback(err);
                    return;
                }

                // TODO: we should use arraybuffer here.
                callback(null, data);
            });
        };

        BlobServerClient.prototype.putMetadata = function (metadataDescriptor, callback) {
            var self = this;
            var metadata = new BlobMetadata(metadataDescriptor);

            var options = {
                hostname: '127.0.0.1',
                port: this.serverPort,
                path: this.getCreateURL(metadata.name, true),
                method: 'POST'
            };

            self._sendHttpRequestWithContent(options, JSON.stringify(metadata.serialize(), null, 4), function (err, data) {
                if (err) {
                    callback(err);
                    return;
                }

                var response = JSON.parse(data);
                // TODO: handle error
                // Get the first one
                var hash = Object.keys(response)[0];
                callback(null, hash);
            });
        };

        BlobServerClient.prototype.putFile = function (name, data, callback) {
            var options = {
                hostname: '127.0.0.1',
                port: this.serverPort,
                path: this.getCreateURL(name),
                method: 'POST'
            };

            this._sendHttpRequestWithContent(options, data, function (err, responseData) {
                if (err) {
                    callback(err);
                    return;
                }

                var response = JSON.parse(responseData);
                // TODO: handle error
                // Get the first one
                var hash = Object.keys(response)[0];
                callback(null, hash);
            });
        };

        // -------------------------------------------------------------------------------------------------------------
        // Private helper functions

        BlobServerClient.prototype._ensureAuthenticated = function (options, callback) {
            //this function enables the session of the client to be authenticated
            //TODO curently this user does not have a session, so it has to upgrade the options always!!!
            if (options.headers) {
                options.headers.webgmeclientsession = this._clientSession;
            } else {
                options.headers = {
                    'webgmeclientsession': this._clientSession
                }
            }
            callback(null, options);
        };

        BlobServerClient.prototype._sendHttpRequest = function (options, callback) {
            var self = this;
            self._ensureAuthenticated(options, function (err, updatedOptions) {
                if (err) {
                    callback(err);
                } else {
                    self.__sendHttpRequest(updatedOptions, callback);
                }
            });
        };

        BlobServerClient.prototype.__sendHttpRequest = function (options, callback) {
            // TODO: use the http or https
            var req = http.request(options, function (res) {
                var bufferStream = new StringStreamWriter();

                res.on('end', function () {
                    if (res.statusCode === 200) {
                        callback(null, bufferStream.getBuffer());
                    } else {
                        callback(res.statusCode, bufferStream.getBuffer());
                    }
                });

                res.pipe(bufferStream);

            });

            req.on('error', function (e) {
                callback(e);
            });

            req.end();
        };

        BlobServerClient.prototype._sendHttpRequestWithContent = function (options, data, callback) {
            var self = this;
            self._ensureAuthenticated(options, function (err, updatedOptions) {
                if (err) {
                    callback(err);
                } else {
                    self.__sendHttpRequestWithContent(updatedOptions, data, callback);
                }
            });
        };

        BlobServerClient.prototype.__sendHttpRequestWithContent = function (options, data, callback) {
            // TODO: use the http or https
            var req = http.request(options, function (res) {
                //    console.log('STATUS: ' + res.statusCode);
                //    console.log('HEADERS: ' + JSON.stringify(res.headers));
                //    res.setEncoding('utf8');
                var d = '';
                res.on('data', function (chunk) {
                    d += chunk;
                });

                res.on('end', function () {
                    if (res.statusCode === 200) {
                        callback(null, d);
                    } else {
                        callback(res.statusCode, d);
                    }
                });
            });

            req.on('error', function (e) {
                callback(e);
            });

            // write data to request body
            req.write(data);

            req.end();
        };

        return BlobServerClient;
    });
<commit_msg>BlobServerClient: accept server parameter<commit_after>/*
 * Copyright (C) 2014 Vanderbilt University, All rights reserved.
 *
 * Author: Zsolt Lattmann
 *
 * Server side BLOB client implementation.
 */

define(['blob/BlobClient', 'blob/BlobMetadata', 'http', 'https', 'util/StringStreamWriter'],
    function (BlobClient, BlobMetadata, http, https, StringStreamWriter) {

        /**
         * Initializes a new instance of a server side blob client that makes http requests.
         *
         * Note: This code strictly runs in node.js (server side).
         *
         * @param {{}} parameters
         * @constructor
         */
        function BlobServerClient(parameters) {
            BlobClient.call(this);
            this.server = parameters.server || '127.0.0.1';
            this.serverPort = parameters.serverPort;
            this._clientSession = parameters.sessionId;
        }

        // Inherits from BlobClient
        BlobServerClient.prototype = Object.create(BlobClient.prototype);

        // Override the constructor with this object's constructor
        BlobServerClient.prototype.constructor = BlobServerClient;

        BlobServerClient.prototype.getMetadata = function (hash, callback) {
            var options = {
                hostname: this.server,
                port: this.serverPort,
                path: this.getMetadataURL(hash),
                method: 'GET'
            };

            this._sendHttpRequest(options, function (err, data) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, JSON.parse(data));
            });
        };

        BlobServerClient.prototype.getObject = function (hash, callback) {
            var options = {
                hostname: this.server,
                port: this.serverPort,
                path: this.getViewURL(hash),
                method: 'GET'
            };

            this._sendHttpRequest(options, function (err, data) {
                if (err) {
                    callback(err);
                    return;
                }

                // TODO: we should use arraybuffer here.
                callback(null, data);
            });
        };

        BlobServerClient.prototype.putMetadata = function (metadataDescriptor, callback) {
            var self = this;
            var metadata = new BlobMetadata(metadataDescriptor);

            var options = {
                hostname: this.server,
                port: this.serverPort,
                path: this.getCreateURL(metadata.name, true),
                method: 'POST'
            };

            self._sendHttpRequestWithContent(options, JSON.stringify(metadata.serialize(), null, 4), function (err, data) {
                if (err) {
                    callback(err);
                    return;
                }

                var response = JSON.parse(data);
                // TODO: handle error
                // Get the first one
                var hash = Object.keys(response)[0];
                callback(null, hash);
            });
        };

        BlobServerClient.prototype.putFile = function (name, data, callback) {
            var options = {
                hostname: this.server,
                port: this.serverPort,
                path: this.getCreateURL(name),
                method: 'POST'
            };

            this._sendHttpRequestWithContent(options, data, function (err, responseData) {
                if (err) {
                    callback(err);
                    return;
                }

                var response = JSON.parse(responseData);
                // TODO: handle error
                // Get the first one
                var hash = Object.keys(response)[0];
                callback(null, hash);
            });
        };

        // -------------------------------------------------------------------------------------------------------------
        // Private helper functions

        BlobServerClient.prototype._ensureAuthenticated = function (options, callback) {
            //this function enables the session of the client to be authenticated
            //TODO curently this user does not have a session, so it has to upgrade the options always!!!
            if (options.headers) {
                options.headers.webgmeclientsession = this._clientSession;
            } else {
                options.headers = {
                    'webgmeclientsession': this._clientSession
                }
            }
            callback(null, options);
        };

        BlobServerClient.prototype._sendHttpRequest = function (options, callback) {
            var self = this;
            self._ensureAuthenticated(options, function (err, updatedOptions) {
                if (err) {
                    callback(err);
                } else {
                    self.__sendHttpRequest(updatedOptions, callback);
                }
            });
        };

        BlobServerClient.prototype.__sendHttpRequest = function (options, callback) {
            // TODO: use the http or https
            var req = http.request(options, function (res) {
                var bufferStream = new StringStreamWriter();

                res.on('end', function () {
                    if (res.statusCode === 200) {
                        callback(null, bufferStream.getBuffer());
                    } else {
                        callback(res.statusCode, bufferStream.getBuffer());
                    }
                });

                res.pipe(bufferStream);

            });

            req.on('error', function (e) {
                callback(e);
            });

            req.end();
        };

        BlobServerClient.prototype._sendHttpRequestWithContent = function (options, data, callback) {
            var self = this;
            self._ensureAuthenticated(options, function (err, updatedOptions) {
                if (err) {
                    callback(err);
                } else {
                    self.__sendHttpRequestWithContent(updatedOptions, data, callback);
                }
            });
        };

        BlobServerClient.prototype.__sendHttpRequestWithContent = function (options, data, callback) {
            // TODO: use the http or https
            var req = http.request(options, function (res) {
                //    console.log('STATUS: ' + res.statusCode);
                //    console.log('HEADERS: ' + JSON.stringify(res.headers));
                //    res.setEncoding('utf8');
                var d = '';
                res.on('data', function (chunk) {
                    d += chunk;
                });

                res.on('end', function () {
                    if (res.statusCode === 200) {
                        callback(null, d);
                    } else {
                        callback(res.statusCode, d);
                    }
                });
            });

            req.on('error', function (e) {
                callback(e);
            });

            // write data to request body
            req.write(data);

            req.end();
        };

        return BlobServerClient;
    });
<|endoftext|>


<commit_before>// __tests__/Input.js

import React from 'react';
import { mount } from 'enzyme';
import Input from '../Input.js';
import { getSingleSpecWrapper } from "../../../util/tests/data-spec.js";

const generateComponent = (additionalProps={}) => (
    <Input {...additionalProps} />
);

it('Password input allows <> in field', () => {
  // Render a password with <> in the value
  const passwordInput = mount(
    <Input name="password" defaultValue="1234<>" />
  );

  expect(passwordInput.instance().getValue()).toEqual("1234<>");
});

it('Name input does not allow <> in field', () => {
  // Render a input with <> in the value
  const passwordInput = mount(
    <Input name="something" defaultValue="1234<>" />
  );

  expect(passwordInput.instance().getValue()).toEqual("1234");
});

it ("should render with no props", () => {
  let component = mount(generateComponent());
  expect(component.html()).toMatchSnapshot();
});

// XXX should input ID be the label? Can contain spaces
it ("should accept label prop", () => {
  let component = mount(generateComponent({
    label: "test label"
  }));
  expect(component.find("label").text()).toEqual("test label");
});

it ("should accept name prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    name: "myname"
  }));

  const labelProps = component.find("label").props();
  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(labelProps.htmlFor).toEqual("myname");
  expect(inputProps.name).toEqual("myname");
  expect(inputProps.id).toEqual("myname");
});

it ("should accept id prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    name: "myname",
    id: "myid"
  }));

  const labelProps = component.find("label").props();
  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(labelProps.htmlFor).toEqual("myid");
  expect(inputProps.id).toEqual("myid");
});

it ("should accept hideLabel prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    hideLabel: true
  }));

  expect(component.find("label").length).toEqual(0);
});

it ("should accept defaultValue", () => {
  let component = mount(generateComponent({
    label: "test label",
    hideLabel: true,
    defaultValue: "test value"
  }));

  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(inputProps.defaultValue).toEqual("test value");
});

// XXX Need to test label has disabled prop.
it ("should accept disabled prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    disabled: true
  }));

  // const inputHTML = getSingleSpecWrapper(component, "input").html();
  const inputProps = getSingleSpecWrapper(component, "input").props();

  // expect(inputHTML).toContain("disabled=\"\"");
  // expect(inputHTML).toContain("cursor: inherit");
  expect(inputProps.disabled).toEqual(true);
  expect(inputProps.style).toEqual({"cursor": "inherit"});
});

it ("should accept type prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text"
  }));

  // const inputHTML = getSingleSpecWrapper(component, "input").html();
  const inputProps = getSingleSpecWrapper(component, "input").props();

  // expect(inputHTML).toContain("type=\"text\"");
  expect(inputProps.type).toEqual("text");
});

it ("should accept classes prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    classes: "testClass"
  }));

  let componentArr = mount(generateComponent({
    label: "test label",
    type: "text",
    classes: ["test1", "test2"]
  }));

  const wrapper = getSingleSpecWrapper(component, "input-wrapper");
  const wrapper2 = getSingleSpecWrapper(componentArr, "input-wrapper");

  expect(wrapper.hasClass("testClass")).toEqual(true);
  expect(wrapper2.hasClass("test2")).toEqual(true);
});

it ("should accept inputClasses prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    inputClasses: "testClass"
  }));

  const input = getSingleSpecWrapper(component, "input");

  expect(input.hasClass("testClass")).toEqual(true);
});

it ("should accept style prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    style: {backgroundColor: "red"}
  }));

  // const wrapperHTML = getSingleSpecWrapper(component, "input-wrapper").html();
  const wrapperProps = getSingleSpecWrapper(component, "input-wrapper").props();

  // expect(wrapperHTML).toContain("background-color: red");
  expect(wrapperProps.style).toEqual({"backgroundColor": "red"});
});

it ("should accept placeholder prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    placeholder: "harambe"
  }));

  const inputProps = getSingleSpecWrapper(component,"input").props();

  expect(inputProps.placeholder).toEqual("harambe");
});

it ("should accept children", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    children: "hey there!"
  }));

  expect(component.html()).toContain("hey there!");
});

it ("should accept maxLength prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    maxLength: 10
  }));

  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(inputProps.maxLength).toEqual(10);
});

it ("should accept autofocus prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    autofocus: true
  }));

  expect(component.state("focused")).toEqual(true);
});

it ("should accept onChange prop", () => {
  const spy = jest.fn();
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    onChange: spy
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("change");
  expect(spy).toBeCalled();
});

it ("should accept onBlur prop", () => {
  const spy = jest.fn();
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    onBlur: spy
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("focus");
  input.simulate("blur");
  expect(spy).toBeCalled();
});

it ("should accept validation prop", () => {
  const spy = jest.fn();
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    validation: spy
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("focus");
  input.simulate("blur");
  expect(spy).toBeCalled();
});

it ("should accept format prop", () => {
  const spy = jest.fn();
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    format: spy
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("change");
  expect(spy).toBeCalled();
});

it ("should accept errorText prop", () => {
  //simulate error in validation
  const spy = jest.fn().mockReturnValue(false);
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    validation: spy,
    errorText: "my text"
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("focus");
  input.simulate("blur"); //validation calls after blur
  expect(spy).toBeCalled();

  const help = getSingleSpecWrapper(component, "help");

  expect(help.text()).toEqual("my text");
});

// TODO
// it ("should accept value prop", () => {
//   let component = mount(generateComponent({
//     label: "test label",
//     type: "text",
//     value: "harambe"
//   }));

//   component.simulate("focus");
//   component.simulate("change");
//   component.simulate("blur");
//   console.log(component.html());
//   const wrapperHTML = getSingleSpecWrapper(component, "input-wrapper").html();
// });
<commit_msg>removed comments<commit_after>// __tests__/Input.js

import React from 'react';
import { mount } from 'enzyme';
import Input from '../Input.js';
import { getSingleSpecWrapper } from "../../../util/tests/data-spec.js";

const generateComponent = (additionalProps={}) => (
    <Input {...additionalProps} />
);

it('Password input allows <> in field', () => {
  // Render a password with <> in the value
  const passwordInput = mount(
    <Input name="password" defaultValue="1234<>" />
  );

  expect(passwordInput.instance().getValue()).toEqual("1234<>");
});

it('Name input does not allow <> in field', () => {
  // Render a input with <> in the value
  const passwordInput = mount(
    <Input name="something" defaultValue="1234<>" />
  );

  expect(passwordInput.instance().getValue()).toEqual("1234");
});

it ("should render with no props", () => {
  let component = mount(generateComponent());
  expect(component.html()).toMatchSnapshot();
});

// XXX should input ID be the label? Can contain spaces
it ("should accept label prop", () => {
  let component = mount(generateComponent({
    label: "test label"
  }));
  expect(component.find("label").text()).toEqual("test label");
});

it ("should accept name prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    name: "myname"
  }));

  const labelProps = component.find("label").props();
  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(labelProps.htmlFor).toEqual("myname");
  expect(inputProps.name).toEqual("myname");
  expect(inputProps.id).toEqual("myname");
});

it ("should accept id prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    name: "myname",
    id: "myid"
  }));

  const labelProps = component.find("label").props();
  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(labelProps.htmlFor).toEqual("myid");
  expect(inputProps.id).toEqual("myid");
});

it ("should accept hideLabel prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    hideLabel: true
  }));

  expect(component.find("label").length).toEqual(0);
});

it ("should accept defaultValue", () => {
  let component = mount(generateComponent({
    label: "test label",
    hideLabel: true,
    defaultValue: "test value"
  }));

  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(inputProps.defaultValue).toEqual("test value");
});

// XXX Need to test label has disabled prop.
it ("should accept disabled prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    disabled: true
  }));

  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(inputProps.disabled).toEqual(true);
  expect(inputProps.style).toEqual({"cursor": "inherit"});
});

it ("should accept type prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text"
  }));

  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(inputProps.type).toEqual("text");
});

it ("should accept classes prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    classes: "testClass"
  }));

  let componentArr = mount(generateComponent({
    label: "test label",
    type: "text",
    classes: ["test1", "test2"]
  }));

  const wrapper = getSingleSpecWrapper(component, "input-wrapper");
  const wrapper2 = getSingleSpecWrapper(componentArr, "input-wrapper");

  expect(wrapper.hasClass("testClass")).toEqual(true);
  expect(wrapper2.hasClass("test2")).toEqual(true);
});

it ("should accept inputClasses prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    inputClasses: "testClass"
  }));

  const input = getSingleSpecWrapper(component, "input");

  expect(input.hasClass("testClass")).toEqual(true);
});

it ("should accept style prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    style: {backgroundColor: "red"}
  }));

  const wrapperProps = getSingleSpecWrapper(component, "input-wrapper").props();

  expect(wrapperProps.style).toEqual({"backgroundColor": "red"});
});

it ("should accept placeholder prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    placeholder: "harambe"
  }));

  const inputProps = getSingleSpecWrapper(component,"input").props();

  expect(inputProps.placeholder).toEqual("harambe");
});

it ("should accept children", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    children: "hey there!"
  }));

  expect(component.html()).toContain("hey there!");
});

it ("should accept maxLength prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    maxLength: 10
  }));

  const inputProps = getSingleSpecWrapper(component, "input").props();

  expect(inputProps.maxLength).toEqual(10);
});

it ("should accept autofocus prop", () => {
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    autofocus: true
  }));

  expect(component.state("focused")).toEqual(true);
});

it ("should accept onChange prop", () => {
  const spy = jest.fn();
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    onChange: spy
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("change");
  expect(spy).toBeCalled();
});

it ("should accept onBlur prop", () => {
  const spy = jest.fn();
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    onBlur: spy
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("focus");
  input.simulate("blur");
  expect(spy).toBeCalled();
});

it ("should accept validation prop", () => {
  const spy = jest.fn();
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    validation: spy
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("focus");
  input.simulate("blur");
  expect(spy).toBeCalled();
});

it ("should accept format prop", () => {
  const spy = jest.fn();
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    format: spy
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("change");
  expect(spy).toBeCalled();
});

it ("should accept errorText prop", () => {
  //simulate error in validation
  const spy = jest.fn().mockReturnValue(false);
  let component = mount(generateComponent({
    label: "test label",
    type: "text",
    validation: spy,
    errorText: "my text"
  }));

  const input = getSingleSpecWrapper(component, "input");

  input.simulate("focus");
  input.simulate("blur"); //validation calls after blur
  expect(spy).toBeCalled();

  const help = getSingleSpecWrapper(component, "help");

  expect(help.text()).toEqual("my text");
});

// TODO
// it ("should accept value prop", () => {
//   let component = mount(generateComponent({
//     label: "test label",
//     type: "text",
//     value: "harambe"
//   }));

//   component.simulate("focus");
//   component.simulate("change");
//   component.simulate("blur");
//   console.log(component.html());
//   const wrapperHTML = getSingleSpecWrapper(component, "input-wrapper").html();
// });
<|endoftext|>


<commit_before>jQuery(function($) {

	/* ==========================================================================
	   Exponential Widths
	   ========================================================================== */

		function exponential() {
			var view = $(window).width();
			var flubber = $('.inner');

			var shot = Math.sqrt(view);
			shot = 100 - shot * view / 1000;

			if(shot < 62.51) {
				shot = 62.5;
			} else if (shot > 89.999) {
				shot = 90;
			}

			flubber.css({
				'width'	: shot + '%'
			});
		}
		exponential();
		$(window).resize(exponential);

	/* ==========================================================================
	   Fitvids by Chris Coyier
	   ========================================================================== */

	$('#wrapper').fitVids();

	/* ==========================================================================
	   Ajax Loading by Rory Gibson
	   ========================================================================== */

    var History = window.History;
    var loading = false;
    var showIndex = true;
    var $ajaxContainer = $('#ajax-container');
    var $postIndex = $('#post-index');

    // Initially hide the index and show the latest post
    $postIndex.show();

    // Show the index if the url has "page" in it (a simple
    // way of checking if we're on a paginated page.)
    if (window.location.pathname.indexOf('page') === 1) {
        $postIndex.show();
    }

    // Check if history is enabled for the browser
    if ( ! History.enabled) {
        return false;
    }

    History.Adapter.bind(window, 'statechange', function() {
        var State = History.getState();

        // Get the requested url and replace the current content
        // with the loaded content
        $.get(State.url, function(result) {
            var $html = $(result);
            var $newContent = $('#ajax-container', $html).contents();

            $('html, body').animate({'scrollTop': 0});

            $ajaxContainer.fadeOut(500, function() {
                $postIndex = $newContent.filter('#post-index');

                if (showIndex === true) {
                } else {
                    $postIndex.hide();
                }

                $ajaxContainer.html($newContent);
                $ajaxContainer.fadeIn(500);
				$('#site-footer').fadeIn(100);

                NProgress.done();
                exponential();
                $('#wrapper').fitVids();

                loading = false;
                showIndex = false;
            });
        });
    });

    $('body').on('click', '.js-ajax-link, .pagination a', function(e) {
        e.preventDefault();

        if (loading === false) {
            var currentState = History.getState();
            var url = $(this).attr('href');
            var title = $(this).attr('title') || null;

            // If the requested url is not the current states url push
            // the new state and make the ajax call.
            if (url !== currentState.url.replace(/\/$/, "")) {
                loading = true;

                // Check if we need to show the post index after we've
                // loaded the new content
                if ($(this).hasClass('js-show-index') || $(this).parent('.pagination').length > 0) {
                    showIndex = true;
                }
                if ($(this).hasClass('post-link')) {
					$('.post').animate({
						'margin-top' : '-' + 5 + 'em',
						'padding' : 0.5 + 'em 0',
						'opacity' : '0'
					}, 500);
					$('#site-footer').fadeOut(100);
				} else if($(this).hasClass('js-show-index')) {
					$('.post').animate({
						'margin-top' : '-' + 20 + 'em',
						'opacity' : '0'
					}, 500);
					$('#site-footer').fadeOut(100);
				}
                NProgress.start();

                History.pushState({}, title, url);
            } else {

                // Swap in the latest post or post index as needed
                if (!$(this).hasClass('js-show-index')) {
                    $('html, body').animate({'scrollTop': 0});

                    NProgress.start();

                    $postIndex.fadeOut(300, function() {
                        NProgress.done();
                    });
                }
            }
        }
    });

});
<commit_msg>ajax detects if current page is single<commit_after>jQuery(function($) {

	/* ==========================================================================
	   Exponential Widths
	   ========================================================================== */

		function exponential() {
			var view = $(window).width();
			var flubber = $('.inner');

			var shot = Math.sqrt(view);
			shot = 100 - shot * view / 1000;

			if(shot < 62.51) {
				shot = 62.5;
			} else if (shot > 89.999) {
				shot = 90;
			}

			flubber.css({
				'width'	: shot + '%'
			});
		}
		exponential();
		$(window).resize(exponential);

	/* ==========================================================================
	   Fitvids by Chris Coyier
	   ========================================================================== */

	$('#wrapper').fitVids();

	/* ==========================================================================
	   Ajax Loading by Rory Gibson
	   ========================================================================== */

    var History = window.History;
    var loading = false;
    var showIndex = true;
    var $ajaxContainer = $('#ajax-container');
    var $postIndex = $('#post-index');
    var $blogLink = $('.js-show-index');

    // Initially hide the index and show the latest post
    $postIndex.show();

    // Show the index if the url has "page" in it (a simple
    // way of checking if we're on a paginated page.)
    if (window.location.pathname.indexOf('page') === 1) {
        $postIndex.show();
    }

    // Check if history is enabled for the browser
    if ( ! History.enabled) {
        return false;
    }

    History.Adapter.bind(window, 'statechange', function() {
        var State = History.getState();

        // Get the requested url and replace the current content
        // with the loaded content
        $.get(State.url, function(result) {
            var $html = $(result);
            var $newContent = $('#ajax-container', $html).contents();

            $('html, body').animate({'scrollTop': 0});

            $ajaxContainer.fadeOut(500, function() {
                $postIndex = $newContent.filter('#post-index');

                if (showIndex === true) {
                } else {
                    $postIndex.hide();
                }

                $ajaxContainer.html($newContent);
                $ajaxContainer.fadeIn(500);
				$('#site-footer').fadeIn(100);

                NProgress.done();
                exponential();
                $('#wrapper').fitVids();

                loading = false;
                showIndex = false;
            });
        });
    });

    $('body').on('click', '.js-ajax-link, .pagination a', function(e) {
        e.preventDefault();

        if (loading === false) {
            var currentState = History.getState();
            var url = $(this).attr('href');
            var title = $(this).attr('title') || null;

            // If the requested url is not the current states url push
            // the new state and make the ajax call.
            if (url !== currentState.url.replace(/\/$/, "")) {
                loading = true;

                // Check if we need to show the post index after we've
                // loaded the new content
                if ($(this).hasClass('js-show-index') || $(this).parent('.pagination').length > 0) {
                    showIndex = true;
                }
                if ($(this).hasClass('post-link')) {
					$('.post').animate({
						'margin-top' : '-' + 5 + 'em',
						'padding' : 0.5 + 'em 0',
						'opacity' : '0'
					}, 500);
					$('#site-footer').fadeOut(100);
					$blogLink.addClass('single');
				} else if($(this).hasClass('js-show-index')) {
					if($(this).hasClass('single')) {
						$('.post').animate({
							'margin-top' : '-' + 20 + 'em',
							'opacity' : '0'
						}, 500);
						$('#site-footer').fadeOut(100);
					}
					$blogLink.removeClass('single');
				}
                NProgress.start();

                History.pushState({}, title, url);
            } else {

                // Swap in the latest post or post index as needed
                if (!$(this).hasClass('js-show-index')) {
                    $('html, body').animate({'scrollTop': 0});

                    NProgress.start();

                    $postIndex.fadeOut(300, function() {
                        NProgress.done();
                    });
                }
            }
        }
    });

});
<|endoftext|>


<commit_before><commit_msg>Update lang-zh_CN.js<commit_after><|endoftext|>


<commit_before>// BOOKMARKLET GENERATOR
var script = "var scriptUrl='//cdn.rawgit.com/codealchemist/torrent-helper-bookmarklet/master/torrent-helper.bookmarklet.js';",
	js="javascript:(function(){ " + script + "var protocol = location.protocol;var bookmarkletUrl = protocol + scriptUrl;var script = document.createElement('script');script.src = bookmarkletUrl;document.body.appendChild(script); })()";
	div = document.createElement('div'),
	style="position:fixed; margin: auto; top: 20px; left:0; right:0; padding: 20px; width: 400px; border: 1px solid #ccc; background: white; border-radius: 5px; color: black;";

var html = '' +
	'
' +
	'
Install by dragging the following link to your bookmarks bar:
' +
	'Torrent Helper (github) | ' +
	'close' +
	'
';

div.innerHTML = html;
document.body.appendChild(div);
<commit_msg>removed not needed files.<commit_after><|endoftext|>


<commit_before>/** 8
 * OpenEyes
 *
 * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
 * (C) OpenEyes Foundation, 2011-2013
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust
 * @copyright Copyright (c) 2011-2013, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
 */

(function(exports, Util, EventEmitter) {

	'use strict';
	/**
	 * FieldImages constructor.
	 * @constructor
	 * @name OpenEyes.UI.FieldImages
	 * @memberOf OpenEyes.UI
	 * @extends OpenEyes.Util.EventEmitter
	 * @example
	 * var fieldImages = new OpenEyes.UI.FieldImages({
	 *	images: OpenEyes.Util.FieldImagesList,
	 *	idToImages: array('ElementHTML_id' => OpenEyes.Util.FieldImagesList.property)
	 * });
	 */
	function FieldImages(options) {
		EventEmitter.call(this);
		this.options = $.extend(true, {}, FieldImages._defaultOptions, options);
	}

	Util.inherits(EventEmitter, FieldImages);

	/**
	 * The default dialog options. Custom options will be merged with these.
	 * @name OpenEyes.UI.FieldImages#_defaultOptions
		 * @property {string} [title=null] - Dialog title
		 * @property {array} [images=null] - Images available for fields
	 * @property {array} [idToImages=null] - Html ID to images relation
	 */
	FieldImages._defaultOptions = {
		title: "Field Images",
		images: null,
		idToImages:null,
		dialogInstance:null
	};

	/**
	 * Creates and stores the dialog container, and creates a new jQuery UI
	 * instance on the container.
	 * @name OpenEyes.UI.FieldImages#create
	 * @method
	 * @private
	 */
	FieldImages.prototype.createDiag = function(fieldElId) {
		this.options.dialog = new OpenEyes.UI.Dialog({
			title: this.options.title,
			content: this.createImagesDiv(this.options.idToImages[fieldElId ], fieldElId)
		});
		this.options.dialog.open();
	};

		/**
		 * Creates the Images container
		 * @name OpenEyes.UI.FieldImages#createImagesDiv
		 * @method
		 * @private
		 */
	FieldImages.prototype.createImagesDiv = function(fieldElId, selectId) {
		var wrapper = $('
', {
			'class':  "fieldsWrapper"
		});
		for(var sval in fieldElId['selects']){
			var imgPath = null;
			if(fieldElId['id'] in this.options.images){
/*				if(sval in this.options.images[fieldElId['id']]){
					imgPath = this.options.images[fieldElId['id']][sval];
				}
*/
				imgPath = OE_core_asset_path + '/img/fieldImages/' + fieldElId['id'] + '-' + sval + '.jpg';
			}

			var el = $('
', {
					class: 'ui-field-image'
			}).click({
				selectId: selectId,
				val: sval,
				fieldImgInstance: this
			},function(e) {
				$( "#"+ e.data.selectId).val(e.data.val);
				e.data.fieldImgInstance.options.dialog.close();
			});
			var valPar = $('
' + sval + '
');
			if(imgPath){
				$(el).css("background-image", "url("+ imgPath + ")");
				$(valPar).appendTo(el);
			}
			else{
				$(el).css("background-color", "#999");
				$(valPar).appendTo(el);
				$('
No Preview
').appendTo(el)
			}

			$(el).appendTo(wrapper);
		}
		return wrapper;
	};

	/**
	 * Sets fields  buttons in dom
	 * @name OpenEyes.UI.FieldImages#setFieldButtons
	 * @method
	 * @private
	 */
	FieldImages.prototype.setFieldButtons = function() {
		for (var selectId in this.options.idToImages) {

			if($('#' + selectId)){
				this.options.idToImages[selectId]
				$('', {
					id: selectId + "_cog",
					src: OE_core_asset_path + '/img/_elements/icons/event/small/images_photo.png',
					alt: 'Opens ' + selectId + ' field images',
					'class': 'ui-field-images-icon'
				}).insertAfter( '#' + selectId );

				var this_ = this;

				$( '#' + selectId + "_cog").click( function() {
					var sId = this.id.substr(0, (this.id.length - 4) );
					this_.createDiag( sId);
				});
			}
		}
	};

	exports.FieldImages = FieldImages;

}(OpenEyes.UI, OpenEyes.Util, OpenEyes.Util.EventEmitter));
<commit_msg>OE-5681 missing bleb images<commit_after>/**
 * OpenEyes
 *
 * (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
 * (C) OpenEyes Foundation, 2011-2013
 * This file is part of OpenEyes.
 * OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package OpenEyes
 * @link http://www.openeyes.org.uk
 * @author OpenEyes <info@openeyes.org.uk>
 * @copyright Copyright (c) 2008-2011, Moorfields Eye Hospital NHS Foundation Trust
 * @copyright Copyright (c) 2011-2013, OpenEyes Foundation
 * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
 */

(function(exports, Util, EventEmitter) {

	'use strict';
	/**
	 * FieldImages constructor.
	 * @constructor
	 * @name OpenEyes.UI.FieldImages
	 * @memberOf OpenEyes.UI
	 * @extends OpenEyes.Util.EventEmitter
	 * @example
	 * var fieldImages = new OpenEyes.UI.FieldImages({
	 *	images: OpenEyes.Util.FieldImagesList,
	 *	idToImages: array('ElementHTML_id' => OpenEyes.Util.FieldImagesList.property)
	 * });
	 */
	function FieldImages(options) {
		EventEmitter.call(this);
		this.options = $.extend(true, {}, FieldImages._defaultOptions, options);
	}

	Util.inherits(EventEmitter, FieldImages);

	/**
	 * The default dialog options. Custom options will be merged with these.
	 * @name OpenEyes.UI.FieldImages#_defaultOptions
		 * @property {string} [title=null] - Dialog title
		 * @property {array} [images=null] - Images available for fields
	 * @property {array} [idToImages=null] - Html ID to images relation
	 */
	FieldImages._defaultOptions = {
		title: "Field Images",
		images: null,
		idToImages:null,
		dialogInstance:null
	};

	/**
	 * Creates and stores the dialog container, and creates a new jQuery UI
	 * instance on the container.
	 * @name OpenEyes.UI.FieldImages#create
	 * @method
	 * @private
	 */
	FieldImages.prototype.createDiag = function(fieldElId) {
		this.options.dialog = new OpenEyes.UI.Dialog({
			title: this.options.title,
			content: this.createImagesDiv(this.options.idToImages[fieldElId ], fieldElId)
		});
		this.options.dialog.open();
	};

		/**
		 * Creates the Images container
		 * @name OpenEyes.UI.FieldImages#createImagesDiv
		 * @method
		 * @private
		 */
	FieldImages.prototype.createImagesDiv = function(fieldElId, selectId) {
		var wrapper = $('
', {
			'class':  "fieldsWrapper"
		});
		for(var sval in fieldElId['selects']){
			var imgPath = null;
			if(fieldElId['id'] in this.options.images){
/*				if(sval in this.options.images[fieldElId['id']]){
					imgPath = this.options.images[fieldElId['id']][sval];
				}
*/
				imgPath = OE_core_asset_path + '/img/fieldImages/' + fieldElId['id'] + '-' + sval + '.jpg';
			}

			var el = $('
', {
					class: 'ui-field-image'
			}).click({
				selectId: selectId,
				val: sval,
				fieldImgInstance: this
			},function(e) {
				$( "#"+ e.data.selectId).val(e.data.val);
				e.data.fieldImgInstance.options.dialog.close();
			});
			var valPar = $('
' + sval + '
');
			if(imgPath){
				$(el).css("background-image", "url("+ imgPath + ")");
				$(valPar).appendTo(el);
			}
			else{
				$(el).css("background-color", "#999");
				$(valPar).appendTo(el);
				$('
No Preview
').appendTo(el)
			}

			$(el).appendTo(wrapper);
		}
		return wrapper;
	};

	/**
	 * Sets fields  buttons in dom
	 * @name OpenEyes.UI.FieldImages#setFieldButtons
	 * @method
	 * @private
	 */
	FieldImages.prototype.setFieldButtons = function() {
		for (var selectId in this.options.idToImages) {

			if($('#' + selectId)){
				this.options.idToImages[selectId]
				$('', {
					id: selectId + "_cog",
					src: OE_core_asset_path + '/img/_elements/icons/event/small/images_photo.png',
					alt: 'Opens ' + selectId + ' field images',
					'class': 'ui-field-images-icon'
				}).insertAfter( '#' + selectId );

				var this_ = this;

				$( '#' + selectId + "_cog").click( function() {
					var sId = this.id.substr(0, (this.id.length - 4) );
					this_.createDiag( sId);
				});
			}
		}
	};

	exports.FieldImages = FieldImages;

}(OpenEyes.UI, OpenEyes.Util, OpenEyes.Util.EventEmitter));
<|endoftext|>


<commit_before>ViewController = AppController.extend({
    waitOn: function() {
        return this.subscribe('myRegistrants');
    },
    data: {

    }
});
<commit_msg>Switched to subscriptions and action.<commit_after>ViewController = AppController.extend({
    subscriptions: function() {
        // Subscribe to user registrations
        return this.subscribe('myRegistrants');
    },
    action: function () {
        // Make sure subscriptions are available before rendering
        // Otherwise, show loading template
        if (this.ready()) {
            this.render();
        } else {
            this.render('loading');
        }
    },
    data: function () {
        return Registrants.find();
    }
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import { remove, map, clone } from 'lodash';
import { getImageUrlFromPost, getEditedImageUrl, displayCaption } from '../../helpers';

import './post.scss';

import Tags from '../Tags';
import PostTile from '../PostTile';
import Quantity from '../Quantity';
import TextBlock from '../TextBlock';
import ReviewBlock from '../ReviewBlock';
import StatusButton from '../StatusButton';
import MetaInformation from '../MetaInformation';
import UserInformation from '../Users/UserInformation';

class Post extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    event.preventDefault();

    this.setState({ loading: true });

    this.props.rotate(this.props.post.id)
      .then(() => {
        this.setState({ loading: false });
      });
  }

  getOtherPosts(post) {
    const post_id = post.id;
    const signup = this.props.signup;

    const posts = signup.posts ? signup.posts : post.siblings.data;

    // get array of posts
    const other_posts = clone(posts);

    // find index that has that post_id and remove
    const big_post = remove(other_posts, current_post => current_post.id == post_id);

    // return the rest of the original array
    return other_posts;
  }

  render() {
    const post = this.props.post;
    const caption = displayCaption(post);
    const user = this.props.user ? this.props.user : null;
    const signup = this.props.signup;
    const campaign = this.props.campaign;
    const quantity = post.quantity != null ? post.quantity : 0;

    return (

        {/* Post Images */}

              Original Photo

            {this.props.rotate ?

                {this.state.loading ?

                  :

                }

              : null}

          {this.props.showSiblings ?

              {
                map(this.getOtherPosts(post), (post, key) => <PostTile key={key} details={post} />)
              }

            : null}

        {/* User and Post information */}

          <UserInformation user={user} linkSignup={signup.signup_id}>
            {this.props.showQuantity ?
              <Quantity quantity={quantity} noun={campaign.reportback_info.noun} verb={campaign.reportback_info.verb} />
              : null}

            {this.props.allowHistory ?

                 this.props.showHistory(post.id, e, signup.signup_id)}>Edit | Show History

              : null}

              <TextBlock title="Text" content={displayCaption(post)} />

              <TextBlock title="Why Statement" content={this.props.signup.why_participated} />

          </UserInformation>

        {/* Review block and meta data */}

            <ReviewBlock post={post} onUpdate={this.props.onUpdate} onTag={this.props.onTag} deletePost={this.props.deletePost} />

            <MetaInformation
              title="Meta"
              details={{
                'Post ID': post.id,
                Source: post.source,
                Submitted: new Date(post.created_at).toDateString(),
                'Northstar Id': signup.northstar_id,
              }}
            />

    );
  }
}

Post.propTypes = {
  allowHistory: PropTypes.bool,
  campaign: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  deletePost: PropTypes.func.isRequired,
  onTag: PropTypes.func.isRequired,
  onUpdate: PropTypes.func.isRequired,
  post: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  rotate: PropTypes.func,
  showHistory: PropTypes.func,
  showQuantity: PropTypes.bool,
  showSiblings: PropTypes.bool,
  signup: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  // @TODO: Sometimes comes in as an array, and sometimes as an object.
  // Figure out why, and update the validation.
  user: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.object,
  ]), // eslint-disable-line react/forbid-prop-types
};

Post.defaultProps = {
  allowHistory: false,
  campaign: null,
  rotate: null,
  showHistory: null,
  showQuantity: false,
  showSiblings: false,
  user: null,
};

export default Post;
<commit_msg>updates column sizing and hiding photo depending on type of post<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import { remove, map, clone } from 'lodash';
import { getImageUrlFromPost, getEditedImageUrl, displayCaption } from '../../helpers';

import './post.scss';

import Tags from '../Tags';
import PostTile from '../PostTile';
import Quantity from '../Quantity';
import TextBlock from '../TextBlock';
import ReviewBlock from '../ReviewBlock';
import StatusButton from '../StatusButton';
import MetaInformation from '../MetaInformation';
import UserInformation from '../Users/UserInformation';

class Post extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    event.preventDefault();

    this.setState({ loading: true });

    this.props.rotate(this.props.post.id)
      .then(() => {
        this.setState({ loading: false });
      });
  }

  getOtherPosts(post) {
    const post_id = post.id;
    const signup = this.props.signup;

    const posts = signup.posts ? signup.posts : post.siblings.data;

    // get array of posts
    const other_posts = clone(posts);

    // find index that has that post_id and remove
    const big_post = remove(other_posts, current_post => current_post.id == post_id);

    // return the rest of the original array
    return other_posts;
  }

  render() {
    const post = this.props.post;
    const caption = displayCaption(post);
    const user = this.props.user ? this.props.user : null;
    const signup = this.props.signup;
    const campaign = this.props.campaign;
    const quantity = post.quantity != null ? post.quantity : 0;
    const containerSize = post.type === 'photo' ? '-third' : '-half';

    return (

        {/* Post Images */}
        {post.type === 'photo' ?

                Original Photo

              {this.props.rotate ?

                  {this.state.loading ?

                    :

                  }

                : null}

            {this.props.showSiblings ?

                {
                  map(this.getOtherPosts(post), (post, key) => <PostTile key={key} details={post} />)
                }

              : null}

          : null}

        {/* User and Post information */}

          <UserInformation user={user} linkSignup={signup.signup_id}>
            {this.props.showQuantity ?
              <Quantity quantity={quantity} noun={campaign.reportback_info.noun} verb={campaign.reportback_info.verb} />
              : null}

            {this.props.allowHistory ?

                 this.props.showHistory(post.id, e, signup.signup_id)}>Edit | Show History

              : null}

              <TextBlock title="Text" content={displayCaption(post)} />

              <TextBlock title="Why Statement" content={this.props.signup.why_participated} />

          </UserInformation>

        {/* Review block and meta data */}

            <ReviewBlock post={post} onUpdate={this.props.onUpdate} onTag={this.props.onTag} deletePost={this.props.deletePost} />

            <MetaInformation
              title="Meta"
              details={{
                'Post ID': post.id,
                Source: post.source,
                Submitted: new Date(post.created_at).toDateString(),
                'Northstar Id': signup.northstar_id,
              }}
            />

    );
  }
}

Post.propTypes = {
  allowHistory: PropTypes.bool,
  campaign: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  deletePost: PropTypes.func.isRequired,
  onTag: PropTypes.func.isRequired,
  onUpdate: PropTypes.func.isRequired,
  post: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  rotate: PropTypes.func,
  showHistory: PropTypes.func,
  showQuantity: PropTypes.bool,
  showSiblings: PropTypes.bool,
  signup: PropTypes.object.isRequired, // eslint-disable-line react/forbid-prop-types
  // @TODO: Sometimes comes in as an array, and sometimes as an object.
  // Figure out why, and update the validation.
  user: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.object,
  ]), // eslint-disable-line react/forbid-prop-types
};

Post.defaultProps = {
  allowHistory: false,
  campaign: null,
  rotate: null,
  showHistory: null,
  showQuantity: false,
  showSiblings: false,
  user: null,
};

export default Post;
<|endoftext|>


<commit_before>/**
 * Broadcast updates to client when the model changes
 */

'use strict';

var Wallet = require('./../wallet/wallet.model');
var ripple = require('ripple-lib');

var Remote = ripple.Remote;

// TODO Move this to config
var ROOT_RIPPLE_ACCOUNT = {
  address : 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
  secret  : 'masterpassphrase'
};

// TODO Move this to config
var RIPPLED_WS_SERVER = 'ws://localhost:6006'

function create_wallet(callback) {
  // Wait for randomness to have been added.
  // The entropy of the random generator is increased
  // by random data received from a rippled
  // TODO: This is event is never received?
  // See: https://github.com/ripple/ripple-lib/blob/develop/docs/GUIDES.md
  //remote.connect(function(err, res) {
  //     if (!err) {
  //       console.log('Remote connected');
  //       remote.once('random', function(err, info) {
           var wallet = ripple.Wallet.generate();
           callback(wallet);
  //       });
  //     } else {
  //       console.warn('Creating Ripple Address in offline mode');
  //       var wallet = ripple.Wallet.generate();
  //       callback(wallet);
  //     }
  //    });
}

function fund_wallet(ripple_address, callback, amount) {
  var amount = amount || 60;

  var remote = new Remote({
      // see the API Reference for available options
      servers: [ RIPPLED_WS_SERVER ]
  });

  remote.setSecret(ROOT_RIPPLE_ACCOUNT.address , ROOT_RIPPLE_ACCOUNT.secret);

  var options = { account: ROOT_RIPPLE_ACCOUNT.address,
                  destination: ripple_address,
                  amount : amount * 1000000
                };
  remote.connect(function(err, res) {
    if (!err) {
        console.log('Remote connected');
        var transaction = remote.createTransaction('Payment', options);
        transaction.submit(function (err, res) {
            if (err) {
                console.log('Failed to make initial XRP transfer because: ' +
                              err);
            }
            if (res) {
              console.log('Successfully funded wallet ' + ripple_address +
                          ' with 60 XRP');
            }
          });
    } else {
      console.error('Remote not connected');
    }
  });
}

exports.create_wallet = create_wallet;
exports.fund_wallet = fund_wallet;

exports.register = function(socket) {
  socket.on('create_wallet', function(data) {
      create_wallet(function(ripple_wallet) {
      var wallet = {
        ownerEmail: data.ownerEmail,
        publicKey: ripple_wallet.address,
        passphrase: ripple_wallet.secret,
      };

      Wallet.create(wallet, function(err, wallet) {
        if(!err) {
          socket.emit('post:create_wallet', null, wallet.publicKey);
        } else {
          socket.emit('post:create_wallet', 'error', null);
          console.error(err);
        }
      });

      fund_wallet(ripple_wallet.address);
    });
  });
}
<commit_msg>create wallet in DB after funsing with XRP<commit_after>/**
 * Broadcast updates to client when the model changes
 */

'use strict';

var Wallet = require('./../wallet/wallet.model');
var ripple = require('ripple-lib');

var Remote = ripple.Remote;

// TODO Move this to config
var ROOT_RIPPLE_ACCOUNT = {
  address : 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
  secret  : 'masterpassphrase'
};

// TODO Move this to config
var RIPPLED_WS_SERVER = 'ws://localhost:6006'

function create_wallet(callback) {
  // Wait for randomness to have been added.
  // The entropy of the random generator is increased
  // by random data received from a rippled
  // TODO: This is event is never received?
  // See: https://github.com/ripple/ripple-lib/blob/develop/docs/GUIDES.md
  //remote.connect(function(err, res) {
  //     if (!err) {
  //       console.log('Remote connected');
  //       remote.once('random', function(err, info) {
           var wallet = ripple.Wallet.generate();
           callback(wallet);
  //       });
  //     } else {
  //       console.warn('Creating Ripple Address in offline mode');
  //       var wallet = ripple.Wallet.generate();
  //       callback(wallet);
  //     }
  //    });
}

function fund_wallet(wallet, socket, callback, amount) {
  var amount = amount || 60;

  var remote = new Remote({
      // see the API Reference for available options
      servers: [ RIPPLED_WS_SERVER ]
  });

  remote.setSecret(ROOT_RIPPLE_ACCOUNT.address , ROOT_RIPPLE_ACCOUNT.secret);

  var ripple_address = wallet.publicKey;
  var options = { account: ROOT_RIPPLE_ACCOUNT.address,
                  destination: ripple_address,
                  amount : amount * 1000000
                };
  remote.connect(function(err, res) {
    if (!err) {
        console.log('Remote connected');
        var transaction = remote.createTransaction('Payment', options);
        transaction.submit(function (err, res) {
            if (err) {
                console.log('Failed to make initial XRP transfer because: ' +
                              err);
            }
            if (res) {
              console.log('Successfully funded wallet ' + ripple_address +
                          ' with 60 XRP');
              if (callback && socket) {
                callback(wallet, socket);
              }
            }
          });
    } else {
      console.error('Remote not connected');
    }
  });
}

function save_wallet_to_db(wallet, socket) {
  Wallet.create(wallet, function(err, wallet) {
    if(!err) {
      socket.emit('post:create_wallet', null, wallet.publicKey);
    } else {
      socket.emit('post:create_wallet', 'error', null);
      console.error(err);
    }
  });
}

exports.create_wallet = create_wallet;
exports.fund_wallet = fund_wallet;

exports.register = function(socket) {
  socket.on('create_wallet', function(data) {
      create_wallet(function(ripple_wallet) {
      var wallet = {
        ownerEmail: data.ownerEmail,
        publicKey: ripple_wallet.address,
        passphrase: ripple_wallet.secret,
      };

      fund_wallet(wallet, socket, save_wallet_to_db);
    });
  });
}
<|endoftext|>


<commit_before>define([

  'Backbone',

  //Collection
  'app/collections/tasks',

  //View
  'app/views/taskItemView',
  'app/views/TaskDetail',

  //Template
  'text!templates/project-page/taskItemTemplate.html',
], function(

  Backbone,

  //Collection
  Tasks,

  //View
  taskItemView,
  TaskDetail,

  //Template
  itemTemplate
){

  var TaskController = Backbone.View.extend({

    template: _.template(itemTemplate),

    initialize: function(){
      this.collection =  new Tasks(this.options.projectId);
      this.collection.bind('reset add remove change', this.render, this);
      this.collection.bind('search', this.searchResult, this);

      this.taskDetail = new TaskDetail({
        collection: this.collection,
        router: this.options.router
      });

    },

    searchResult: function(result){
      this.$el.html('');

      var template = this.template;
      var $list    = this.$el;
      var title, task;

      _.each(result, function(model){
        title = model.get('title');

        if(title){
          task = new taskItemView({ model: model });
          $list.append(task.el);
        }
      });
    },

    render: function(){
      this.$el.html('');

      var template = this.template;
      var $list    = this.$el;
      var task;

      _.each(this.collection.models, function(model){
        task = new taskItemView({ model: model });
        $list.append(task.el);
      });
    }
  });

  return TaskController;

});
<commit_msg>Fix name of taskDetail<commit_after>define([

  'Backbone',

  //Collection
  'app/collections/tasks',

  //View
  'app/views/taskItemView',
  'app/views/taskDetail',

  //Template
  'text!templates/project-page/taskItemTemplate.html',
], function(

  Backbone,

  //Collection
  Tasks,

  //View
  taskItemView,
  TaskDetail,

  //Template
  itemTemplate
){

  var TaskController = Backbone.View.extend({

    template: _.template(itemTemplate),

    initialize: function(){
      this.collection =  new Tasks(this.options.projectId);
      this.collection.bind('reset add remove change', this.render, this);
      this.collection.bind('search', this.searchResult, this);

      this.taskDetail = new TaskDetail({
        collection: this.collection,
        router: this.options.router
      });

    },

    searchResult: function(result){
      this.$el.html('');

      var template = this.template;
      var $list    = this.$el;
      var title, task;

      _.each(result, function(model){
        title = model.get('title');

        if(title){
          task = new taskItemView({ model: model });
          $list.append(task.el);
        }
      });
    },

    render: function(){
      this.$el.html('');

      var template = this.template;
      var $list    = this.$el;
      var task;

      _.each(this.collection.models, function(model){
        task = new taskItemView({ model: model });
        $list.append(task.el);
      });
    }
  });

  return TaskController;

});
<|endoftext|>