<commit_before>GetShowOffCommentFromJsonString = function(jsonString) {

  console.log("get showoffcomment from json string: " + JSON.stringify(jsonString));
  var userId = jsonString["authorId"];
  console.log("get userid from json string : " + userId);
  var parseId;
  if(userId == undefined){
    result = {
      result: false,
      error: "property not found: userId"
    };
    return result;
  }
  else{
    var user =  Meteor.users.findOne({_id: userId});
    if(user == undefined){
      result = {
        result: false,
        error: "user not found"
      };
      return result;
    }
    else{
      parseId = user.parseId;
    }
  }

  var parentId = jsonString["parentId"];
  if (!parentId) {
    return;
  };
  var isParentPost = jsonString["isRootComment"];
  var parentLevel = 0;
  if (!isParentPost) {
    var parentComment = ShowoffComments.findOne({_id: parentId});
    parentLevel = parentComment.level;
  };

  var providePostCommentProperties = ['authorId', 'commentContent', 'parentId', 'showOffId'];
  var defaultShowOffComment = {
    createdAt: new Date(),
    postedAt: new Date(),
    downvoters: [],
    downvotes: 0,
    upvoters: [],
    upvotes: 0,
    inactive: true,
    level: 1 + parentLevel,
    userId: userId,
    parseId: parseId,
    isRootComment: isParentPost ? true: false
  };

  var newShowOffComment = defaultShowOffComment;
  var res = true;
  var missingProperty;
  providePostCommentProperties.forEach(function(property) {

      newShowOffComment[property] = jsonString[property];
  });

  var result;
  if (!res) {
    result = {
      result: false,
      error: "property is not found: " + missingProperty
    };
  } else {
    result = {
      result: true,
      newShowOffComment: newShowOffComment
    };
  }
  return result;
};

uploadShowOffComment = function(newShowOffComment, response) {

  console.log("new showoff comment :" + newShowOffComment)
  var userId = newShowOffComment.userId;
  var showOffId = newShowOffComment.showOffId;
  var showOffItem = Showoffs.findOne({
    _id: showOffId
  });

  if (!showOffItem) {
    var result = {
      result: false,
      error: "no showoff found"
    };
    response.write(JSON.stringify(result));
    response.end();
  };

  var numberOfComments = showOffItem.commentConut + 1;
  console.log("update comment number :" + numberOfComments);
    Showoffs.update({
      _id: showOffId
    },
    {
      $set:{commentConut: numberOfComments},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };

        response.write(JSON.stringify(result));
        response.end();
      }
    })

  ShowoffComments.insert(newShowOffComment, function(error, newShowOffCommentID) {
    if (error) {
      var result = {
        result: false,
        error: error.reason
      };
      response.write(JSON.stringify(result));
    } else {
      var result = {
        result: true,
        newShowOffCommentID: newShowOffCommentID
      };
      response.write(JSON.stringify(result));
    }
    response.end();
  })
};

GetShowOffComments = function(showOffId, userId, limitSegment, skip) {
  var showOffComments = [];
  var limit = typeof limitSegment === 'undefined' ? 20 : limitSegment // default limit: 20 showoffs
  skip = typeof skip === 'undefined' ? 0 : skip;
  console.log("will get showoff comments  "  + " limit " + limit + " skip " + skip + " showOffId  " + showOffId + " userId " + userId);

    if(showOffId){
      ShowoffComments.find({showOffId: showOffId}, {sort: {postedAt: 1}, limit: limit,skip: skip}).forEach(function(showOffCommentItem) {
      showOffCommentItem["hasUpvoted"] = showOffCommentItem.upvoters != undefined ? (showOffCommentItem.upvoters.contains(userId)? true: false) : false;
      showOffCommentItem["hasDownVoted"] = showOffCommentItem.downvoters != undefined ? (showOffCommentItem.downvoters.contains(userId)? true: false) : false;
      showOffCommentItem["commentId"] = showOffCommentItem._id;

      if(showOffCommentItem.authorId != undefined){
        var user = Meteor.users.findOne({_id: showOffCommentItem.authorId});
        if (user != undefined) {
          showOffCommentItem["authorFaceURL"] = user.avatar;
          showOffCommentItem["authorName"] = user.username;
        }
        else{
          showOffCommentItem["authorFaceURL"] = "";
        }
      }

      if(showOffCommentItem["level"] == undefined){
        showOffCommentItem["level"] = 1;
      }
      delete showOffCommentItem.upvoters;
      delete showOffCommentItem.downvoters;
      showOffComments.push(showOffCommentItem);
    });

    for(var i = 0 ; i < showOffComments.length; i++){

      var comment = showOffComments[i];
      var insertIndex = i;
      showOffComments.filter(function(subComment){
        return subComment.parentId === comment._id
      }).forEach(function(subComment){
        insertIndex++;
        var subIndex = showOffComments.indexOf(subComment);
        if(subIndex != insertIndex){
          showOffComments.move(subIndex, insertIndex);
        }
      });
    }
  }
  var res = {
    showOffComments: showOffComments
  };
  return JSON.stringify(res);
};

LikeShowOffComment = function(commentId, userId, response) {

  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

  var user = Meteor.users.findOne({
    _id: userId
  });
  var commentItem = ShowoffComments.findOne({
    _id: commentId
  });

  if (user && commentItem) {
    //unhate
    var haters = commentItem.downvoters;
    var hates = commentItem.downvotes;
    var hasHated = false;
    var hateIndex;
    for (var i = haters.length - 1; i >= 0; i--) {
      if (haters[i] == userId) {

        hasHated = true;
        hateIndex = i;
      };
    };

    if (hasHated) {
      hates --;
      haters.splice(hateIndex,1);

      ShowoffComments.update({
        _id: commentId
      },
      {
        $set:{downvoter: hates,downvoters: haters},
      }, function(error) {});
    };

    //like
    var likers = commentItem.upvoters;
    var likes = commentItem.upvotes;
    for (var i = likers.length - 1; i >= 0; i--) {
      if (likers[i] == userId) {

          response.write(JSON.stringify({
            result: false,
            error: "upVoted before"
          }));
          response.end();
      };
    };

    likes ++;
    likers.push(userId);

    ShowoffComments.update({
      _id: commentId
    },
    {
      $set:{upvotes: likes,upvoters: likers},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };
      } else {
        result = {
          result: true
        };
      }
      response.write(JSON.stringify(result));
      response.end();
    })

  }
  else{
    response.write(JSON.stringify({
      result: false,
      error: "wrong params"
    }));
    response.end();
  };
}

UnLikeShowOffComment = function(commentId, userId, response) {

  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

  console.log("will unlike showoff comment");

  var user = Meteor.users.findOne({
    _id: userId
  });
  var commentItem = ShowoffComments.findOne({
    _id: commentId
  });

  if (user && commentItem) {
    var likers = commentItem.upvoters;
    var likes = commentItem.upvotes;
    var hasLiked = false;
    var likeIndex;
    console.log("likers :" + likers);
    for (var i = likers.length - 1; i >= 0; i--) {
      console.log("liker :" + likers[i] + ",user :" + userId);
      if (likers[i] == userId) {

        hasLiked = true;
        likeIndex = i;
      };
    };

    if (!hasLiked) {
      response.write(JSON.stringify({
        result: false,
        error: "have not upVoted before"
      }));
      response.end();
    };
    likes --;
    likers.splice(likeIndex,1);

    ShowoffComments.update({
      _id: commentId
    },
    {
      $set:{upvotes: likes,upvoters: likers},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };
      } else {
        result = {
          result: true
        };
      }
      response.write(JSON.stringify(result));
      response.end();
    })
  }
  else{
    response.write(JSON.stringify({
      result: false,
      error: "wrong params"
    }));
    response.end();
  };
}

HateShowOffComment = function(commentId, userId, response) {

  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

  var user = Meteor.users.findOne({
    _id: userId
  });
  var commentItem = ShowoffComments.findOne({
    _id: commentId
  });

  if (user && commentItem) {
    //unlike
    var likers = commentItem.upvoters;
    var likes = commentItem.upvotes;
    var hasLiked = false;
    var likeIndex;
    console.log("likers :" + likers);
    for (var i = likers.length - 1; i >= 0; i--) {
      console.log("liker :" + likers[i] + ",user :" + userId);
      if (likers[i] == userId) {

        hasLiked = true;
        likeIndex = i;
      };
    };

    if (hasLiked) {
      likes --;
      likers.splice(likeIndex,1);

      ShowoffComments.update({
        _id: commentId
      },
      {
        $set:{upvotes: likes,upvoters: likers},
      }, function(error) {});
    };

    //hate
    var haters = commentItem.downvoters;
    var hates = commentItem.downvotes;
    for (var i = haters.length - 1; i >= 0; i--) {
      if (haters[i] == userId) {

          response.write(JSON.stringify({
            result: false,
            error: "downVoted before"
          }));
          response.end();
      };
    };

    hates ++;
    haters.push(userId);

    ShowoffComments.update({
      _id: commentId
    },
    {
      $set:{downvotes: hates,downvoters: haters},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };
      } else {
        result = {
          result: true
        };
      }
      response.write(JSON.stringify(result));
      response.end();
    })

  }
  else{
    response.write(JSON.stringify({
      result: false,
      error: "wrong params"
    }));
    response.end();
  };
}

UnHateOffComment = function(commentId, userId, response) {

  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

  var user = Meteor.users.findOne({
    _id: userId
  });
  var commentItem = ShowoffComments.findOne({
    _id: commentId
  });

  if (user && commentItem) {
    var haters = commentItem.downvoters;
    var hates = commentItem.downvotes;
    var hasHated = false;
    var hateIndex;
    for (var i = haters.length - 1; i >= 0; i--) {
      if (haters[i] == userId) {

        hasHated = true;
        hateIndex = i;
      };
    };

    if (!hasHated) {
      response.write(JSON.stringify({
        result: false,
        error: "have not upVoted before"
      }));
      response.end();
    };
    hates --;
    haters.splice(hateIndex,1);

    ShowoffComments.update({
      _id: commentId
    },
    {
      $set:{downvoter: hates,downvoters: haters},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };
      } else {
        result = {
          result: true
        };
      }
      response.write(JSON.stringify(result));
      response.end();
    })
  }
  else{
    response.write(JSON.stringify({
      result: false,
      error: "wrong params"
    }));
    response.end();
  };
}

DeleteOffComment  = function(commentId, userId, response) {
  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

    var deleteComment = ShowoffComments.findOne({_id: commentId});
    if(deleteComment){

      ShowoffComments.remove(deleteComment, function(error){
        if (error) {
          var result = {
            result: false,
            error: error
          };
          response.write(JSON.stringify(result));
          response.end();
        }
        else{

          Showoffs.update({_id: deleteComment.showOffId},{$inc: {commentCount: -1}});
          DeleleSubComments(commentId);
          var result = {
          result: true
          };
          response.write(JSON.stringify(result));
          response.end();
        }
      });
    }
    else{
      var result = {
        result: false,
        reson: "showoffcomment not found"
      };
      response.write(JSON.stringify(result));
      response.end();
    }
}

DeleleSubComments = function(commentId){
  console.log("delete: " + commentId);
  ShowoffComments.find({parentId: commentId}).forEach(function(subComment){
            ShowoffComments.remove(subComment,function(error){
              if(!error){
                Showoffs.update({_id: subComment.showOffId},{$inc: {commentCount: -1}});
              }
            });
            DeleleSubComments(subComment._id);
  });
}<commit_msg>remove possible wrong msg<commit_after>GetShowOffCommentFromJsonString = function(jsonString) {

  console.log("get showoffcomment from json string: " + JSON.stringify(jsonString));
  var userId = jsonString["authorId"];
  console.log("get userid from json string : " + userId);
  var parseId;
  if(userId == undefined){
    result = {
      result: false,
      error: "property not found: userId"
    };
    return result;
  }
  else{
    var user =  Meteor.users.findOne({_id: userId});
    if(user == undefined){
      result = {
        result: false,
        error: "user not found"
      };
      return result;
    }
    else{
      parseId = user.parseId;
    }
  }

  var parentId = jsonString["parentId"];
  if (!parentId) {
    return;
  };
  var isParentPost = jsonString["isRootComment"];
  var parentLevel = 0;
  if (!isParentPost) {
    var parentComment = ShowoffComments.findOne({_id: parentId});
    parentLevel = parentComment.level;
  };

  var providePostCommentProperties = ['authorId', 'commentContent', 'parentId', 'showOffId'];
  var defaultShowOffComment = {
    createdAt: new Date(),
    postedAt: new Date(),
    downvoters: [],
    downvotes: 0,
    upvoters: [],
    upvotes: 0,
    inactive: true,
    level: 1 + parentLevel,
    userId: userId,
    parseId: parseId,
    isRootComment: isParentPost ? true: false
  };

  var newShowOffComment = defaultShowOffComment;
  var res = true;
  var missingProperty;
  providePostCommentProperties.forEach(function(property) {

      newShowOffComment[property] = jsonString[property];
  });

  var result;
  if (!res) {
    result = {
      result: false,
      error: "property is not found: " + missingProperty
    };
  } else {
    result = {
      result: true,
      newShowOffComment: newShowOffComment
    };
  }
  return result;
};

uploadShowOffComment = function(newShowOffComment, response) {

  console.log("new showoff comment :" + newShowOffComment)
  var userId = newShowOffComment.userId;
  var showOffId = newShowOffComment.showOffId;
  var showOffItem = Showoffs.findOne({
    _id: showOffId
  });

  if (!showOffItem) {
    var result = {
      result: false,
      error: "no showoff found"
    };
    response.write(JSON.stringify(result));
    response.end();
  };

  var numberOfComments = showOffItem.commentConut + 1;
  console.log("update comment number :" + numberOfComments);
    Showoffs.update({
      _id: showOffId
    },
    {
      $set:{commentConut: numberOfComments},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };

        response.write(JSON.stringify(result));
        response.end();
      }
    })

  ShowoffComments.insert(newShowOffComment, function(error, newShowOffCommentID) {
    if (error) {
      var result = {
        result: false,
        error: error.reason
      };
      response.write(JSON.stringify(result));
    } else {
      var result = {
        result: true,
        newShowOffCommentID: newShowOffCommentID
      };
      response.write(JSON.stringify(result));
    }
    response.end();
  })
};

GetShowOffComments = function(showOffId, userId, limitSegment, skip) {
  var showOffComments = [];
  var limit = typeof limitSegment === 'undefined' ? 20 : limitSegment // default limit: 20 showoffs
  skip = typeof skip === 'undefined' ? 0 : skip;
  console.log("will get showoff comments  "  + " limit " + limit + " skip " + skip + " showOffId  " + showOffId + " userId " + userId);

    if(showOffId){
      ShowoffComments.find({showOffId: showOffId}, {sort: {postedAt: 1}, limit: limit,skip: skip}).forEach(function(showOffCommentItem) {
      showOffCommentItem["hasUpvoted"] = showOffCommentItem.upvoters != undefined ? (showOffCommentItem.upvoters.contains(userId)? true: false) : false;
      showOffCommentItem["hasDownVoted"] = showOffCommentItem.downvoters != undefined ? (showOffCommentItem.downvoters.contains(userId)? true: false) : false;
      showOffCommentItem["commentId"] = showOffCommentItem._id;

      if(showOffCommentItem.authorId != undefined){
        var user = Meteor.users.findOne({_id: showOffCommentItem.authorId});
        if (user != undefined) {
          showOffCommentItem["authorFaceURL"] = user.avatar;
          showOffCommentItem["authorName"] = user.username;
        }
        else{
          showOffCommentItem["authorFaceURL"] = "";
        }
      }

      if(showOffCommentItem["level"] == undefined){
        showOffCommentItem["level"] = 1;
      }
      delete showOffCommentItem.upvoters;
      delete showOffCommentItem.downvoters;
      showOffComments.push(showOffCommentItem);
    });

    for(var i = 0 ; i < showOffComments.length; i++){

      var comment = showOffComments[i];
      var insertIndex = i;
      showOffComments.filter(function(subComment){
        return subComment.parentId === comment._id
      }).forEach(function(subComment){
        insertIndex++;
        var subIndex = showOffComments.indexOf(subComment);
        if(subIndex != insertIndex){
          showOffComments.move(subIndex, insertIndex);
        }
      });
    }
  }
  var res = {
    showOffComments: showOffComments
  };
  return JSON.stringify(res);
};

LikeShowOffComment = function(commentId, userId, response) {

  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

  var user = Meteor.users.findOne({
    _id: userId
  });
  var commentItem = ShowoffComments.findOne({
    _id: commentId
  });

  if (user && commentItem) {
    //unhate
    var haters = commentItem.downvoters;
    var hates = commentItem.downvotes;
    var hasHated = false;
    var hateIndex;
    for (var i = haters.length - 1; i >= 0; i--) {
      if (haters[i] == userId) {

        hasHated = true;
        hateIndex = i;
      };
    };

    if (hasHated) {
      hates --;
      haters.splice(hateIndex,1);

      ShowoffComments.update({
        _id: commentId
      },
      {
        $set:{downvoter: hates,downvoters: haters},
      }, function(error) {});
    };

    //like
    var likers = commentItem.upvoters;
    var likes = commentItem.upvotes;
    for (var i = likers.length - 1; i >= 0; i--) {
      if (likers[i] == userId) {

          response.write(JSON.stringify({
            result: false,
            error: "upVoted before"
          }));
          response.end();
      };
    };

    likes ++;
    likers.push(userId);

    ShowoffComments.update({
      _id: commentId
    },
    {
      $set:{upvotes: likes,upvoters: likers},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };
      } else {
        result = {
          result: true
        };
      }
      response.write(JSON.stringify(result));
      response.end();
    })

  }
  else{
    response.write(JSON.stringify({
      result: false,
      error: "wrong params"
    }));
    response.end();
  };
}

UnLikeShowOffComment = function(commentId, userId, response) {

  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

  console.log("will unlike showoff comment");

  var user = Meteor.users.findOne({
    _id: userId
  });
  var commentItem = ShowoffComments.findOne({
    _id: commentId
  });

  if (user && commentItem) {
    var likers = commentItem.upvoters;
    var likes = commentItem.upvotes;
    var hasLiked = false;
    var likeIndex;
    console.log("likers :" + likers);
    for (var i = likers.length - 1; i >= 0; i--) {
      console.log("liker :" + likers[i] + ",user :" + userId);
      if (likers[i] == userId) {

        hasLiked = true;
        likeIndex = i;
      };
    };

    if (!hasLiked) {
      response.write(JSON.stringify({
        result: false,
        error: "have not upVoted before"
      }));
      response.end();
    };
    likes --;
    likers.splice(likeIndex,1);

    ShowoffComments.update({
      _id: commentId
    },
    {
      $set:{upvotes: likes,upvoters: likers},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };
      } else {
        result = {
          result: true
        };
      }
      response.write(JSON.stringify(result));
      response.end();
    })
  }
  else{
    response.write(JSON.stringify({
      result: false,
      error: "wrong params"
    }));
    response.end();
  };
}

HateShowOffComment = function(commentId, userId, response) {

  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

  var user = Meteor.users.findOne({
    _id: userId
  });
  var commentItem = ShowoffComments.findOne({
    _id: commentId
  });

  if (user && commentItem) {
    //unlike
    var likers = commentItem.upvoters;
    var likes = commentItem.upvotes;
    var hasLiked = false;
    var likeIndex;
    console.log("likers :" + likers);
    for (var i = likers.length - 1; i >= 0; i--) {
      console.log("liker :" + likers[i] + ",user :" + userId);
      if (likers[i] == userId) {

        hasLiked = true;
        likeIndex = i;
      };
    };

    if (hasLiked) {
      likes --;
      likers.splice(likeIndex,1);

      ShowoffComments.update({
        _id: commentId
      },
      {
        $set:{upvotes: likes,upvoters: likers},
      }, function(error) {});
    };

    //hate
    var haters = commentItem.downvoters;
    var hates = commentItem.downvotes;
    for (var i = haters.length - 1; i >= 0; i--) {
      if (haters[i] == userId) {

          response.write(JSON.stringify({
            result: false,
            error: "downVoted before"
          }));
          response.end();
      };
    };

    hates ++;
    haters.push(userId);

    ShowoffComments.update({
      _id: commentId
    },
    {
      $set:{downvotes: hates,downvoters: haters},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };
      } else {
        result = {
          result: true
        };
      }
      response.write(JSON.stringify(result));
      response.end();
    })

  }
  else{
    response.write(JSON.stringify({
      result: false,
      error: "wrong params"
    }));
    response.end();
  };
}

UnHateOffComment = function(commentId, userId, response) {

  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

  var user = Meteor.users.findOne({
    _id: userId
  });
  var commentItem = ShowoffComments.findOne({
    _id: commentId
  });

  if (user && commentItem) {
    var haters = commentItem.downvoters;
    var hates = commentItem.downvotes;
    var hasHated = false;
    var hateIndex;
    for (var i = haters.length - 1; i >= 0; i--) {
      if (haters[i] == userId) {

        hasHated = true;
        hateIndex = i;
      };
    };

    if (!hasHated) {
      response.write(JSON.stringify({
        result: false,
        error: "have not upVoted before"
      }));
      response.end();
    };
    hates --;
    haters.splice(hateIndex,1);

    ShowoffComments.update({
      _id: commentId
    },
    {
      $set:{downvoter: hates,downvoters: haters},
    }, function(error) {
      var result;
      if (error) {
        result = {
          result: false,
          error: error
        };
      } else {
        result = {
          result: true
        };
      }
      response.write(JSON.stringify(result));
      response.end();
    })
  }
  else{
    response.write(JSON.stringify({
      result: false,
      error: "wrong params"
    }));
    response.end();
  };
}

DeleteOffComment  = function(commentId, userId, response) {
  if (!commentId || !userId) {
    result = {
      result: false,
      error: "params error"
    };
    response.write(JSON.stringify(result));
    response.end();
    return;
  }

    var deleteComment = ShowoffComments.findOne({_id: commentId});
    if(deleteComment){

      ShowoffComments.remove(deleteComment, function(error){
        if (error) {
          var result = {
            result: false,
            error: error
          };
          response.write(JSON.stringify(result));
          response.end();
        }
        else{

          Showoffs.update({_id: deleteComment.showOffId},{$inc: {commentCount: -1}});
          //DeleleSubComments(commentId);
          var result = {
            result: true
          };
          response.write(JSON.stringify(result));
          response.end();
        }
      });
    }
    else{
      var result = {
        result: false,
        reson: "showoffcomment not found"
      };
      response.write(JSON.stringify(result));
      response.end();
    }
}

DeleleSubComments = function(commentId){
  console.log("delete: " + commentId);
  ShowoffComments.find({parentId: commentId}).forEach(function(subComment){
            ShowoffComments.remove(subComment,function(error){
              if(!error){
                Showoffs.update({_id: subComment.showOffId},{$inc: {commentCount: -1}});
              }
            });
            DeleleSubComments(subComment._id);
  });
}<|endoftext|>


<commit_before>import {
  BORDER_RADIUS,
  COLOR,
  FONT_FAMILY,
  FONT_SIZE,
  FONT_WEIGHT,
  LENGTH,
  SPACING,
} from "../../consts/types";

export default {
  "tag.borderWidth": {
    type: LENGTH,
    value: {
      ref: "basics.borderWidths.small",
    },
  },
  "tag.borderRadii": {
    type: BORDER_RADIUS,
    value: {
      ref: "basics.borderRadii.pill",
    },
  },
  "tag.hover.haloWidth": {
    type: LENGTH,
    value: {
      ref: "basics.borderWidths.medium",
    },
  },
  "tag.focus.haloWidth": {
    type: LENGTH,
    value: {
      ref: "basics.borderWidths.large",
    },
  },
  "tag.paddingLeft": {
    type: SPACING,
    value: {
      ref: "density.spacings.small",
    },
  },
  "tag.paddingRight": {
    type: SPACING,
    value: {
      ref: "density.spacings.extraSmall",
    },
  },
  "tag.paddingVertical": {
    type: SPACING,
    value: {
      ref: "density.spacings.extraSmall",
    },
  },
  "tag.default.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
    transform: {
      alpha: 0.15,
    },
  },
  "tag.hover.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
    transform: {
      alpha: 0.25,
    },
  },
  "tag.focus.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
    transform: {
      alpha: 0.15,
    },
  },
  "tag.pressed.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
    transform: {
      alpha: 0.35,
    },
  },
  "tag.default.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.transparent",
    },
  },
  "tag.hover.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.transparent",
    },
  },
  "tag.focus.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.transparent",
    },
  },
  "tag.pressed.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.transparent",
    },
  },
  "tag.focus.haloColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.halo.focus",
    },
  },
  "tag.on.default.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.on.default",
    },
  },
  "tag.on.hover.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.on.hover",
    },
  },
  "tag.on.focus.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.on.focus",
    },
  },
  "tag.on.pressed.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.on.default",
    },
    transform: {
      alpha: 0.7,
    },
  },
  "tag.on.default.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.border.on",
    },
  },
  "tag.on.hover.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.border.on",
    },
  },
  "tag.on.focus.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.border.accent",
    },
  },
  "tag.on.pressed.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.border.on",
    },
  },
  "tag.on.focus.haloColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.halo.focus",
    },
  },
  "tag.label.marginRight": {
    type: SPACING,
    value: {
      ref: "density.spacings.extraSmall",
    },
  },
  "tag.label.fontColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.text.default",
    },
  },
  "tag.label.fontFamily": {
    type: FONT_FAMILY,
    value: {
      ref: "basics.fontFamilies.main",
    },
  },
  "tag.label.fontSize": {
    type: FONT_SIZE,
    value: {
      ref: "density.fontSizes.medium",
    },
  },
  "tag.label.fontWeight": {
    type: FONT_WEIGHT,
    value: {
      ref: "basics.fontWeights.medium",
    },
  },
  "tag.closeButton.iconColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
  },
};
<commit_msg>fix: tag.on.pressed.backgroundColor value<commit_after>import {
  BORDER_RADIUS,
  COLOR,
  FONT_FAMILY,
  FONT_SIZE,
  FONT_WEIGHT,
  LENGTH,
  SPACING,
} from "../../consts/types";

export default {
  "tag.borderWidth": {
    type: LENGTH,
    value: {
      ref: "basics.borderWidths.small",
    },
  },
  "tag.borderRadii": {
    type: BORDER_RADIUS,
    value: {
      ref: "basics.borderRadii.pill",
    },
  },
  "tag.hover.haloWidth": {
    type: LENGTH,
    value: {
      ref: "basics.borderWidths.medium",
    },
  },
  "tag.focus.haloWidth": {
    type: LENGTH,
    value: {
      ref: "basics.borderWidths.large",
    },
  },
  "tag.paddingLeft": {
    type: SPACING,
    value: {
      ref: "density.spacings.small",
    },
  },
  "tag.paddingRight": {
    type: SPACING,
    value: {
      ref: "density.spacings.extraSmall",
    },
  },
  "tag.paddingVertical": {
    type: SPACING,
    value: {
      ref: "density.spacings.extraSmall",
    },
  },
  "tag.default.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
    transform: {
      alpha: 0.15,
    },
  },
  "tag.hover.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
    transform: {
      alpha: 0.25,
    },
  },
  "tag.focus.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
    transform: {
      alpha: 0.15,
    },
  },
  "tag.pressed.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
    transform: {
      alpha: 0.35,
    },
  },
  "tag.default.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.transparent",
    },
  },
  "tag.hover.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.transparent",
    },
  },
  "tag.focus.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.transparent",
    },
  },
  "tag.pressed.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.transparent",
    },
  },
  "tag.focus.haloColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.halo.focus",
    },
  },
  "tag.on.default.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.on.default",
    },
  },
  "tag.on.hover.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.on.hover",
    },
  },
  "tag.on.focus.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.on.focus",
    },
  },
  "tag.on.pressed.backgroundColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.background.on.pressed",
    },
    transform: {
      alpha: 0.7,
    },
  },
  "tag.on.default.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.border.on",
    },
  },
  "tag.on.hover.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.border.on",
    },
  },
  "tag.on.focus.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.border.accent",
    },
  },
  "tag.on.pressed.borderColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.border.on",
    },
  },
  "tag.on.focus.haloColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.halo.focus",
    },
  },
  "tag.label.marginRight": {
    type: SPACING,
    value: {
      ref: "density.spacings.extraSmall",
    },
  },
  "tag.label.fontColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.text.default",
    },
  },
  "tag.label.fontFamily": {
    type: FONT_FAMILY,
    value: {
      ref: "basics.fontFamilies.main",
    },
  },
  "tag.label.fontSize": {
    type: FONT_SIZE,
    value: {
      ref: "density.fontSizes.medium",
    },
  },
  "tag.label.fontWeight": {
    type: FONT_WEIGHT,
    value: {
      ref: "basics.fontWeights.medium",
    },
  },
  "tag.closeButton.iconColor": {
    type: COLOR,
    value: {
      ref: "colorScheme.reference.base",
    },
  },
};
<|endoftext|>


<commit_before>import cloudinary from "cloudinary";
import Posts from "meteor/vulcan:posts";
import Users from 'meteor/vulcan:users';
import { addCallback, Utils, getSetting } from 'meteor/vulcan:core';

const Cloudinary = cloudinary.v2;
const uploadSync = Meteor.wrapAsync(Cloudinary.uploader.upload);

Cloudinary.config({
  cloud_name: getSetting("cloudinaryCloudName"),
  api_key: getSetting("cloudinaryAPIKey"),
  api_secret: getSetting("cloudinaryAPISecret"),
  secure: true,
});

const CloudinaryUtils = {

  // send an image URL to Cloudinary and get a cloudinary result object in return
  uploadImage(imageUrl) {
    try {
      var result = uploadSync(Utils.addHttp(imageUrl));
      const data = {
        cloudinaryId: result.public_id,
        result: result,
        urls: CloudinaryUtils.getUrls(result.public_id)
      };
      return data;
    } catch (error) {
      console.log("// Cloudinary upload failed for URL: "+imageUrl); // eslint-disable-line
      console.log(error); // eslint-disable-line
    }
  },

  // generate signed URL for each format based off public_id
  getUrls(cloudinaryId) {
    return getSetting("cloudinaryFormats").map(format => {
      const url = Cloudinary.url(cloudinaryId, {
        width: format.width,
        height: format.height,
        crop: 'fill',
        sign_url: true,
        fetch_format: "auto",
        quality: "auto"
      });
      return {
        name: format.name,
        url: url
      };
    });
  }
};

// methods
Meteor.methods({
  testCloudinaryUpload: function (thumbnailUrl) {
    if (Users.isAdmin(Meteor.user())) {
      thumbnailUrl = typeof thumbnailUrl === "undefined" ? "http://www.telescopeapp.org/images/logo.png" : thumbnailUrl;
      const data = CloudinaryUtils.uploadImage(thumbnailUrl);
      console.log(data); // eslint-disable-line
    }
  },
  cachePostThumbnails: function (limit = 20) {

    if (Users.isAdmin(Meteor.user())) {

      var postsWithUncachedThumbnails = Posts.find({
        thumbnailUrl: { $exists: true },
        originalThumbnailUrl: { $exists: false }
      }, {sort: {createdAt: -1}, limit: limit});

      postsWithUncachedThumbnails.forEach(Meteor.bindEnvironment((post, index) => {

          Meteor.setTimeout(function () {
          console.log(`// ${index}. Caching thumbnail for post “${post.title}” (_id: ${post._id})`); // eslint-disable-line

          const data = CloudinaryUtils.uploadImage(post.thumbnailUrl);
          Posts.update(post._id, {$set:{
            cloudinaryId: data.cloudinaryId,
            cloudinaryUrls: data.urls
          }});

        }, index * 1000);

      }));
    }
  }
});

// post submit callback
function cachePostThumbnailOnSubmit (post) {
  if (getSetting("cloudinaryAPIKey")) {
    if (post.thumbnailUrl) {

      const data = CloudinaryUtils.uploadImage(post.thumbnailUrl);
      if (data) {
        Posts.update(post._id, {$set:{
          cloudinaryId: data.cloudinaryId,
          cloudinaryUrls: data.urls
        }});
      }

    }
  }
}
addCallback("posts.new.async", cachePostThumbnailOnSubmit);

// post edit callback
function cachePostThumbnailOnEdit (newPost, oldPost) {
  if (getSetting("cloudinaryAPIKey")) {
    if (newPost.thumbnailUrl && newPost.thumbnailUrl !== oldPost.thumbnailUrl) {

      const data = CloudinaryUtils.uploadImage(newPost.thumbnailUrl);
      Posts.update(newPost._id, {$set:{
        cloudinaryId: data.cloudinaryId,
        cloudinaryUrls: data.urls
      }});

    }
  }
}
addCallback("posts.edit.async", cachePostThumbnailOnEdit);

export default CloudinaryUtils;
<commit_msg>make Cloudinary callback sync so that mutations can return thumbnail URLs<commit_after>import cloudinary from "cloudinary";
import Posts from "meteor/vulcan:posts";
import Users from 'meteor/vulcan:users';
import { addCallback, Utils, getSetting } from 'meteor/vulcan:core';

const Cloudinary = cloudinary.v2;
const uploadSync = Meteor.wrapAsync(Cloudinary.uploader.upload);

Cloudinary.config({
  cloud_name: getSetting("cloudinaryCloudName"),
  api_key: getSetting("cloudinaryAPIKey"),
  api_secret: getSetting("cloudinaryAPISecret"),
  secure: true,
});

const CloudinaryUtils = {

  // send an image URL to Cloudinary and get a cloudinary result object in return
  uploadImage(imageUrl) {
    try {
      var result = uploadSync(Utils.addHttp(imageUrl));
      const data = {
        cloudinaryId: result.public_id,
        result: result,
        urls: CloudinaryUtils.getUrls(result.public_id)
      };
      return data;
    } catch (error) {
      console.log("// Cloudinary upload failed for URL: "+imageUrl); // eslint-disable-line
      console.log(error); // eslint-disable-line
    }
  },

  // generate signed URL for each format based off public_id
  getUrls(cloudinaryId) {
    return getSetting("cloudinaryFormats").map(format => {
      const url = Cloudinary.url(cloudinaryId, {
        width: format.width,
        height: format.height,
        crop: 'fill',
        sign_url: true,
        fetch_format: "auto",
        quality: "auto"
      });
      return {
        name: format.name,
        url: url
      };
    });
  }
};

// methods
Meteor.methods({
  testCloudinaryUpload: function (thumbnailUrl) {
    if (Users.isAdmin(Meteor.user())) {
      thumbnailUrl = typeof thumbnailUrl === "undefined" ? "http://www.telescopeapp.org/images/logo.png" : thumbnailUrl;
      const data = CloudinaryUtils.uploadImage(thumbnailUrl);
      console.log(data); // eslint-disable-line
    }
  },
  cachePostThumbnails: function (limit = 20) {

    if (Users.isAdmin(Meteor.user())) {

      var postsWithUncachedThumbnails = Posts.find({
        thumbnailUrl: { $exists: true },
        originalThumbnailUrl: { $exists: false }
      }, {sort: {createdAt: -1}, limit: limit});

      postsWithUncachedThumbnails.forEach(Meteor.bindEnvironment((post, index) => {

          Meteor.setTimeout(function () {
          console.log(`// ${index}. Caching thumbnail for post “${post.title}” (_id: ${post._id})`); // eslint-disable-line

          const data = CloudinaryUtils.uploadImage(post.thumbnailUrl);
          Posts.update(post._id, {$set:{
            cloudinaryId: data.cloudinaryId,
            cloudinaryUrls: data.urls
          }});

        }, index * 1000);

      }));
    }
  }
});

// post submit callback
function cachePostThumbnailOnSubmit (post) {
  if (getSetting("cloudinaryAPIKey")) {
    if (post.thumbnailUrl) {

      const data = CloudinaryUtils.uploadImage(post.thumbnailUrl);
      if (data) {
        post.cloudinaryId = data.cloudinaryId;
        post.cloudinaryUrls = data.urls;
      }

    }
  }
  return post;
}
addCallback("posts.new.sync", cachePostThumbnailOnSubmit);

function cachePostThumbnailOnEdit (modifier, oldPost) {
  if (getSetting("cloudinaryAPIKey")) {
    if (modifier.$set.thumbnailUrl && modifier.$set.thumbnailUrl !== oldPost.thumbnailUrl) {
      const data = CloudinaryUtils.uploadImage(modifier.$set.thumbnailUrl);
      modifier.$set.cloudinaryId = data.cloudinaryId;
      modifier.$set.cloudinaryUrls = data.urls;
    }
  }
  return modifier;
}
addCallback("posts.edit.sync", cachePostThumbnailOnEdit);

export default CloudinaryUtils;
<|endoftext|>


<commit_before>/**
@module ember
@submodule ember-runtime
*/
import Ember from "ember-metal/core"; // Ember.assert

import {get, getWithDefault} from "ember-metal/property_get";
import {set} from "ember-metal/property_set";
import {apply} from "ember-metal/utils";
import getProperties from "ember-metal/get_properties";
import setProperties from "ember-metal/set_properties";
import {Mixin} from "ember-metal/mixin";
import {hasListeners} from "ember-metal/events";
import {beginPropertyChanges, propertyWillChange, propertyDidChange, endPropertyChanges} from "ember-metal/property_events";
import {addObserver, addBeforeObserver, removeObserver, observersFor} from "ember-metal/observer";
import {cacheFor} from "ember-metal/computed";
import {isNone} from "ember-metal/is_none";

var slice = Array.prototype.slice;
/**
  ## Overview

  This mixin provides properties and property observing functionality, core
  features of the Ember object model.

  Properties and observers allow one object to observe changes to a
  property on another object. This is one of the fundamental ways that
  models, controllers and views communicate with each other in an Ember
  application.

  Any object that has this mixin applied can be used in observer
  operations. That includes `Ember.Object` and most objects you will
  interact with as you write your Ember application.

  Note that you will not generally apply this mixin to classes yourself,
  but you will use the features provided by this module frequently, so it
  is important to understand how to use it.

  ## Using `get()` and `set()`

  Because of Ember's support for bindings and observers, you will always
  access properties using the get method, and set properties using the
  set method. This allows the observing objects to be notified and
  computed properties to be handled properly.

  More documentation about `get` and `set` are below.

  ## Observing Property Changes

  You typically observe property changes simply by adding the `observes`
  call to the end of your method declarations in classes that you write.
  For example:

  ```javascript
  Ember.Object.extend({
    valueObserver: function() {
      // Executes whenever the "value" property changes
    }.observes('value')
  });
  ```

  Although this is the most common way to add an observer, this capability
  is actually built into the `Ember.Object` class on top of two methods
  defined in this mixin: `addObserver` and `removeObserver`. You can use
  these two methods to add and remove observers yourself if you need to
  do so at runtime.

  To add an observer for a property, call:

  ```javascript
  object.addObserver('propertyKey', targetObject, targetAction)
  ```

  This will call the `targetAction` method on the `targetObject` whenever
  the value of the `propertyKey` changes.

  Note that if `propertyKey` is a computed property, the observer will be
  called when any of the property dependencies are changed, even if the
  resulting value of the computed property is unchanged. This is necessary
  because computed properties are not computed until `get` is called.

  @class Observable
  @namespace Ember
*/
var Observable = Mixin.create({

  /**
    Retrieves the value of a property from the object.

    This method is usually similar to using `object[keyName]` or `object.keyName`,
    however it supports both computed properties and the unknownProperty
    handler.

    Because `get` unifies the syntax for accessing all these kinds
    of properties, it can make many refactorings easier, such as replacing a
    simple property with a computed property, or vice versa.

    ### Computed Properties

    Computed properties are methods defined with the `property` modifier
    declared at the end, such as:

    ```javascript
    fullName: function() {
      return this.get('firstName') + ' ' + this.get('lastName');
    }.property('firstName', 'lastName')
    ```

    When you call `get` on a computed property, the function will be
    called and the return value will be returned instead of the function
    itself.

    ### Unknown Properties

    Likewise, if you try to call `get` on a property whose value is
    `undefined`, the `unknownProperty()` method will be called on the object.
    If this method returns any value other than `undefined`, it will be returned
    instead. This allows you to implement "virtual" properties that are
    not defined upfront.

    @method get
    @param {String} keyName The property to retrieve
    @return {Object} The property value or undefined.
  */
  get: function(keyName) {
    return get(this, keyName);
  },

  /**
    To get multiple properties at once, call `getProperties`
    with a list of strings or an array:

    ```javascript
    record.getProperties('firstName', 'lastName', 'zipCode');  // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
    ```

    is equivalent to:

    ```javascript
    record.getProperties(['firstName', 'lastName', 'zipCode']);  // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
    ```

    @method getProperties
    @param {String...|Array} list of keys to get
    @return {Hash}
  */
  getProperties: function() {
    return apply(null, getProperties, [this].concat(slice.call(arguments)));
  },

  /**
    Sets the provided key or path to the value.

    This method is generally very similar to calling `object[key] = value` or
    `object.key = value`, except that it provides support for computed
    properties, the `setUnknownProperty()` method and property observers.

    ### Computed Properties

    If you try to set a value on a key that has a computed property handler
    defined (see the `get()` method for an example), then `set()` will call
    that method, passing both the value and key instead of simply changing
    the value itself. This is useful for those times when you need to
    implement a property that is composed of one or more member
    properties.

    ### Unknown Properties

    If you try to set a value on a key that is undefined in the target
    object, then the `setUnknownProperty()` handler will be called instead. This
    gives you an opportunity to implement complex "virtual" properties that
    are not predefined on the object. If `setUnknownProperty()` returns
    undefined, then `set()` will simply set the value on the object.

    ### Property Observers

    In addition to changing the property, `set()` will also register a property
    change with the object. Unless you have placed this call inside of a
    `beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers
    (i.e. observer methods declared on the same object), will be called
    immediately. Any "remote" observers (i.e. observer methods declared on
    another object) will be placed in a queue and called at a later time in a
    coalesced manner.

    ### Chaining

    In addition to property changes, `set()` returns the value of the object
    itself so you can do chaining like this:

    ```javascript
    record.set('firstName', 'Charles').set('lastName', 'Jolley');
    ```

    @method set
    @param {String} keyName The property to set
    @param {Object} value The value to set or `null`.
    @return {Ember.Observable}
  */
  set: function(keyName, value) {
    set(this, keyName, value);
    return this;
  },

  /**
    Sets a list of properties at once. These properties are set inside
    a single `beginPropertyChanges` and `endPropertyChanges` batch, so
    observers will be buffered.

    ```javascript
    record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
    ```

    @method setProperties
    @param {Hash} hash the hash of keys and values to set
    @return {Ember.Observable}
  */
  setProperties: function(hash) {
    return setProperties(this, hash);
  },

  /**
    Begins a grouping of property changes.

    You can use this method to group property changes so that notifications
    will not be sent until the changes are finished. If you plan to make a
    large number of changes to an object at one time, you should call this
    method at the beginning of the changes to begin deferring change
    notifications. When you are done making changes, call
    `endPropertyChanges()` to deliver the deferred change notifications and end
    deferring.

    @method beginPropertyChanges
    @return {Ember.Observable}
  */
  beginPropertyChanges: function() {
    beginPropertyChanges();
    return this;
  },

  /**
    Ends a grouping of property changes.

    You can use this method to group property changes so that notifications
    will not be sent until the changes are finished. If you plan to make a
    large number of changes to an object at one time, you should call
    `beginPropertyChanges()` at the beginning of the changes to defer change
    notifications. When you are done making changes, call this method to
    deliver the deferred change notifications and end deferring.

    @method endPropertyChanges
    @return {Ember.Observable}
  */
  endPropertyChanges: function() {
    endPropertyChanges();
    return this;
  },

  /**
    Notify the observer system that a property is about to change.

    Sometimes you need to change a value directly or indirectly without
    actually calling `get()` or `set()` on it. In this case, you can use this
    method and `propertyDidChange()` instead. Calling these two methods
    together will notify all observers that the property has potentially
    changed value.

    Note that you must always call `propertyWillChange` and `propertyDidChange`
    as a pair. If you do not, it may get the property change groups out of
    order and cause notifications to be delivered more often than you would
    like.

    @method propertyWillChange
    @param {String} keyName The property key that is about to change.
    @return {Ember.Observable}
  */
  propertyWillChange: function(keyName) {
    propertyWillChange(this, keyName);
    return this;
  },

  /**
    Notify the observer system that a property has just changed.

    Sometimes you need to change a value directly or indirectly without
    actually calling `get()` or `set()` on it. In this case, you can use this
    method and `propertyWillChange()` instead. Calling these two methods
    together will notify all observers that the property has potentially
    changed value.

    Note that you must always call `propertyWillChange` and `propertyDidChange`
    as a pair. If you do not, it may get the property change groups out of
    order and cause notifications to be delivered more often than you would
    like.

    @method propertyDidChange
    @param {String} keyName The property key that has just changed.
    @return {Ember.Observable}
  */
  propertyDidChange: function(keyName) {
    propertyDidChange(this, keyName);
    return this;
  },

  /**
    Convenience method to call `propertyWillChange` and `propertyDidChange` in
    succession.

    @method notifyPropertyChange
    @param {String} keyName The property key to be notified about.
    @return {Ember.Observable}
  */
  notifyPropertyChange: function(keyName) {
    this.propertyWillChange(keyName);
    this.propertyDidChange(keyName);
    return this;
  },

  addBeforeObserver: function(key, target, method) {
    addBeforeObserver(this, key, target, method);
  },

  /**
    Adds an observer on a property.

    This is the core method used to register an observer for a property.

    Once you call this method, any time the key's value is set, your observer
    will be notified. Note that the observers are triggered any time the
    value is set, regardless of whether it has actually changed. Your
    observer should be prepared to handle that.

    You can also pass an optional context parameter to this method. The
    context will be passed to your observer method whenever it is triggered.
    Note that if you add the same target/method pair on a key multiple times
    with different context parameters, your observer will only be called once
    with the last context you passed.

    ### Observer Methods

    Observer methods you pass should generally have the following signature if
    you do not pass a `context` parameter:

    ```javascript
    fooDidChange: function(sender, key, value, rev) { };
    ```

    The sender is the object that changed. The key is the property that
    changes. The value property is currently reserved and unused. The rev
    is the last property revision of the object when it changed, which you can
    use to detect if the key value has really changed or not.

    If you pass a `context` parameter, the context will be passed before the
    revision like so:

    ```javascript
    fooDidChange: function(sender, key, value, context, rev) { };
    ```

    Usually you will not need the value, context or revision parameters at
    the end. In this case, it is common to write observer methods that take
    only a sender and key value as parameters or, if you aren't interested in
    any of these values, to write an observer that has no parameters at all.

    @method addObserver
    @param {String} key The key to observer
    @param {Object} target The target object to invoke
    @param {String|Function} method The method to invoke.
    @return {Ember.Object} self
  */
  addObserver: function(key, target, method) {
    addObserver(this, key, target, method);
  },

  /**
    Remove an observer you have previously registered on this object. Pass
    the same key, target, and method you passed to `addObserver()` and your
    target will no longer receive notifications.

    @method removeObserver
    @param {String} key The key to observer
    @param {Object} target The target object to invoke
    @param {String|Function} method The method to invoke.
    @return {Ember.Observable} receiver
  */
  removeObserver: function(key, target, method) {
    removeObserver(this, key, target, method);
  },

  /**
    Returns `true` if the object currently has observers registered for a
    particular key. You can use this method to potentially defer performing
    an expensive action until someone begins observing a particular property
    on the object.

    @method hasObserverFor
    @param {String} key Key to check
    @return {Boolean}
  */
  hasObserverFor: function(key) {
    return hasListeners(this, key+':change');
  },

  /**
    Retrieves the value of a property, or a default value in the case that the
    property returns `undefined`.

    ```javascript
    person.getWithDefault('lastName', 'Doe');
    ```

    @method getWithDefault
    @param {String} keyName The name of the property to retrieve
    @param {Object} defaultValue The value to return if the property value is undefined
    @return {Object} The property value or the defaultValue.
  */
  getWithDefault: function(keyName, defaultValue) {
    return getWithDefault(this, keyName, defaultValue);
  },

  /**
    Set the value of a property to the current value plus some amount.

    ```javascript
    person.incrementProperty('age');
    team.incrementProperty('score', 2);
    ```

    @method incrementProperty
    @param {String} keyName The name of the property to increment
    @param {Number} increment The amount to increment by. Defaults to 1
    @return {Number} The new property value
  */
  incrementProperty: function(keyName, increment) {
    if (isNone(increment)) { increment = 1; }
    Ember.assert("Must pass a numeric value to incrementProperty", (!isNaN(parseFloat(increment)) && isFinite(increment)));
    set(this, keyName, (parseFloat(get(this, keyName)) || 0) + increment);
    return get(this, keyName);
  },

  /**
    Set the value of a property to the current value minus some amount.

    ```javascript
    player.decrementProperty('lives');
    orc.decrementProperty('health', 5);
    ```

    @method decrementProperty
    @param {String} keyName The name of the property to decrement
    @param {Number} decrement The amount to decrement by. Defaults to 1
    @return {Number} The new property value
  */
  decrementProperty: function(keyName, decrement) {
    if (isNone(decrement)) { decrement = 1; }
    Ember.assert("Must pass a numeric value to decrementProperty", (!isNaN(parseFloat(decrement)) && isFinite(decrement)));
    set(this, keyName, (get(this, keyName) || 0) - decrement);
    return get(this, keyName);
  },

  /**
    Set the value of a boolean property to the opposite of it's
    current value.

    ```javascript
    starship.toggleProperty('warpDriveEngaged');
    ```

    @method toggleProperty
    @param {String} keyName The name of the property to toggle
    @return {Object} The new property value
  */
  toggleProperty: function(keyName) {
    set(this, keyName, !get(this, keyName));
    return get(this, keyName);
  },

  /**
    Returns the cached value of a computed property, if it exists.
    This allows you to inspect the value of a computed property
    without accidentally invoking it if it is intended to be
    generated lazily.

    @method cacheFor
    @param {String} keyName
    @return {Object} The cached value of the computed property, if any
  */
  cacheFor: function(keyName) {
    return cacheFor(this, keyName);
  },

  // intended for debugging purposes
  observersForKey: function(keyName) {
    return observersFor(this, keyName);
  }
});

export default Observable;
<commit_msg>[DOC release] Observable addObserver and removeObserver return void.<commit_after>/**
@module ember
@submodule ember-runtime
*/
import Ember from "ember-metal/core"; // Ember.assert

import {get, getWithDefault} from "ember-metal/property_get";
import {set} from "ember-metal/property_set";
import {apply} from "ember-metal/utils";
import getProperties from "ember-metal/get_properties";
import setProperties from "ember-metal/set_properties";
import {Mixin} from "ember-metal/mixin";
import {hasListeners} from "ember-metal/events";
import {beginPropertyChanges, propertyWillChange, propertyDidChange, endPropertyChanges} from "ember-metal/property_events";
import {addObserver, addBeforeObserver, removeObserver, observersFor} from "ember-metal/observer";
import {cacheFor} from "ember-metal/computed";
import {isNone} from "ember-metal/is_none";

var slice = Array.prototype.slice;
/**
  ## Overview

  This mixin provides properties and property observing functionality, core
  features of the Ember object model.

  Properties and observers allow one object to observe changes to a
  property on another object. This is one of the fundamental ways that
  models, controllers and views communicate with each other in an Ember
  application.

  Any object that has this mixin applied can be used in observer
  operations. That includes `Ember.Object` and most objects you will
  interact with as you write your Ember application.

  Note that you will not generally apply this mixin to classes yourself,
  but you will use the features provided by this module frequently, so it
  is important to understand how to use it.

  ## Using `get()` and `set()`

  Because of Ember's support for bindings and observers, you will always
  access properties using the get method, and set properties using the
  set method. This allows the observing objects to be notified and
  computed properties to be handled properly.

  More documentation about `get` and `set` are below.

  ## Observing Property Changes

  You typically observe property changes simply by adding the `observes`
  call to the end of your method declarations in classes that you write.
  For example:

  ```javascript
  Ember.Object.extend({
    valueObserver: function() {
      // Executes whenever the "value" property changes
    }.observes('value')
  });
  ```

  Although this is the most common way to add an observer, this capability
  is actually built into the `Ember.Object` class on top of two methods
  defined in this mixin: `addObserver` and `removeObserver`. You can use
  these two methods to add and remove observers yourself if you need to
  do so at runtime.

  To add an observer for a property, call:

  ```javascript
  object.addObserver('propertyKey', targetObject, targetAction)
  ```

  This will call the `targetAction` method on the `targetObject` whenever
  the value of the `propertyKey` changes.

  Note that if `propertyKey` is a computed property, the observer will be
  called when any of the property dependencies are changed, even if the
  resulting value of the computed property is unchanged. This is necessary
  because computed properties are not computed until `get` is called.

  @class Observable
  @namespace Ember
*/
var Observable = Mixin.create({

  /**
    Retrieves the value of a property from the object.

    This method is usually similar to using `object[keyName]` or `object.keyName`,
    however it supports both computed properties and the unknownProperty
    handler.

    Because `get` unifies the syntax for accessing all these kinds
    of properties, it can make many refactorings easier, such as replacing a
    simple property with a computed property, or vice versa.

    ### Computed Properties

    Computed properties are methods defined with the `property` modifier
    declared at the end, such as:

    ```javascript
    fullName: function() {
      return this.get('firstName') + ' ' + this.get('lastName');
    }.property('firstName', 'lastName')
    ```

    When you call `get` on a computed property, the function will be
    called and the return value will be returned instead of the function
    itself.

    ### Unknown Properties

    Likewise, if you try to call `get` on a property whose value is
    `undefined`, the `unknownProperty()` method will be called on the object.
    If this method returns any value other than `undefined`, it will be returned
    instead. This allows you to implement "virtual" properties that are
    not defined upfront.

    @method get
    @param {String} keyName The property to retrieve
    @return {Object} The property value or undefined.
  */
  get: function(keyName) {
    return get(this, keyName);
  },

  /**
    To get multiple properties at once, call `getProperties`
    with a list of strings or an array:

    ```javascript
    record.getProperties('firstName', 'lastName', 'zipCode');  // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
    ```

    is equivalent to:

    ```javascript
    record.getProperties(['firstName', 'lastName', 'zipCode']);  // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
    ```

    @method getProperties
    @param {String...|Array} list of keys to get
    @return {Hash}
  */
  getProperties: function() {
    return apply(null, getProperties, [this].concat(slice.call(arguments)));
  },

  /**
    Sets the provided key or path to the value.

    This method is generally very similar to calling `object[key] = value` or
    `object.key = value`, except that it provides support for computed
    properties, the `setUnknownProperty()` method and property observers.

    ### Computed Properties

    If you try to set a value on a key that has a computed property handler
    defined (see the `get()` method for an example), then `set()` will call
    that method, passing both the value and key instead of simply changing
    the value itself. This is useful for those times when you need to
    implement a property that is composed of one or more member
    properties.

    ### Unknown Properties

    If you try to set a value on a key that is undefined in the target
    object, then the `setUnknownProperty()` handler will be called instead. This
    gives you an opportunity to implement complex "virtual" properties that
    are not predefined on the object. If `setUnknownProperty()` returns
    undefined, then `set()` will simply set the value on the object.

    ### Property Observers

    In addition to changing the property, `set()` will also register a property
    change with the object. Unless you have placed this call inside of a
    `beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers
    (i.e. observer methods declared on the same object), will be called
    immediately. Any "remote" observers (i.e. observer methods declared on
    another object) will be placed in a queue and called at a later time in a
    coalesced manner.

    ### Chaining

    In addition to property changes, `set()` returns the value of the object
    itself so you can do chaining like this:

    ```javascript
    record.set('firstName', 'Charles').set('lastName', 'Jolley');
    ```

    @method set
    @param {String} keyName The property to set
    @param {Object} value The value to set or `null`.
    @return {Ember.Observable}
  */
  set: function(keyName, value) {
    set(this, keyName, value);
    return this;
  },

  /**
    Sets a list of properties at once. These properties are set inside
    a single `beginPropertyChanges` and `endPropertyChanges` batch, so
    observers will be buffered.

    ```javascript
    record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
    ```

    @method setProperties
    @param {Hash} hash the hash of keys and values to set
    @return {Ember.Observable}
  */
  setProperties: function(hash) {
    return setProperties(this, hash);
  },

  /**
    Begins a grouping of property changes.

    You can use this method to group property changes so that notifications
    will not be sent until the changes are finished. If you plan to make a
    large number of changes to an object at one time, you should call this
    method at the beginning of the changes to begin deferring change
    notifications. When you are done making changes, call
    `endPropertyChanges()` to deliver the deferred change notifications and end
    deferring.

    @method beginPropertyChanges
    @return {Ember.Observable}
  */
  beginPropertyChanges: function() {
    beginPropertyChanges();
    return this;
  },

  /**
    Ends a grouping of property changes.

    You can use this method to group property changes so that notifications
    will not be sent until the changes are finished. If you plan to make a
    large number of changes to an object at one time, you should call
    `beginPropertyChanges()` at the beginning of the changes to defer change
    notifications. When you are done making changes, call this method to
    deliver the deferred change notifications and end deferring.

    @method endPropertyChanges
    @return {Ember.Observable}
  */
  endPropertyChanges: function() {
    endPropertyChanges();
    return this;
  },

  /**
    Notify the observer system that a property is about to change.

    Sometimes you need to change a value directly or indirectly without
    actually calling `get()` or `set()` on it. In this case, you can use this
    method and `propertyDidChange()` instead. Calling these two methods
    together will notify all observers that the property has potentially
    changed value.

    Note that you must always call `propertyWillChange` and `propertyDidChange`
    as a pair. If you do not, it may get the property change groups out of
    order and cause notifications to be delivered more often than you would
    like.

    @method propertyWillChange
    @param {String} keyName The property key that is about to change.
    @return {Ember.Observable}
  */
  propertyWillChange: function(keyName) {
    propertyWillChange(this, keyName);
    return this;
  },

  /**
    Notify the observer system that a property has just changed.

    Sometimes you need to change a value directly or indirectly without
    actually calling `get()` or `set()` on it. In this case, you can use this
    method and `propertyWillChange()` instead. Calling these two methods
    together will notify all observers that the property has potentially
    changed value.

    Note that you must always call `propertyWillChange` and `propertyDidChange`
    as a pair. If you do not, it may get the property change groups out of
    order and cause notifications to be delivered more often than you would
    like.

    @method propertyDidChange
    @param {String} keyName The property key that has just changed.
    @return {Ember.Observable}
  */
  propertyDidChange: function(keyName) {
    propertyDidChange(this, keyName);
    return this;
  },

  /**
    Convenience method to call `propertyWillChange` and `propertyDidChange` in
    succession.

    @method notifyPropertyChange
    @param {String} keyName The property key to be notified about.
    @return {Ember.Observable}
  */
  notifyPropertyChange: function(keyName) {
    this.propertyWillChange(keyName);
    this.propertyDidChange(keyName);
    return this;
  },

  addBeforeObserver: function(key, target, method) {
    addBeforeObserver(this, key, target, method);
  },

  /**
    Adds an observer on a property.

    This is the core method used to register an observer for a property.

    Once you call this method, any time the key's value is set, your observer
    will be notified. Note that the observers are triggered any time the
    value is set, regardless of whether it has actually changed. Your
    observer should be prepared to handle that.

    You can also pass an optional context parameter to this method. The
    context will be passed to your observer method whenever it is triggered.
    Note that if you add the same target/method pair on a key multiple times
    with different context parameters, your observer will only be called once
    with the last context you passed.

    ### Observer Methods

    Observer methods you pass should generally have the following signature if
    you do not pass a `context` parameter:

    ```javascript
    fooDidChange: function(sender, key, value, rev) { };
    ```

    The sender is the object that changed. The key is the property that
    changes. The value property is currently reserved and unused. The rev
    is the last property revision of the object when it changed, which you can
    use to detect if the key value has really changed or not.

    If you pass a `context` parameter, the context will be passed before the
    revision like so:

    ```javascript
    fooDidChange: function(sender, key, value, context, rev) { };
    ```

    Usually you will not need the value, context or revision parameters at
    the end. In this case, it is common to write observer methods that take
    only a sender and key value as parameters or, if you aren't interested in
    any of these values, to write an observer that has no parameters at all.

    @method addObserver
    @param {String} key The key to observer
    @param {Object} target The target object to invoke
    @param {String|Function} method The method to invoke.
  */
  addObserver: function(key, target, method) {
    addObserver(this, key, target, method);
  },

  /**
    Remove an observer you have previously registered on this object. Pass
    the same key, target, and method you passed to `addObserver()` and your
    target will no longer receive notifications.

    @method removeObserver
    @param {String} key The key to observer
    @param {Object} target The target object to invoke
    @param {String|Function} method The method to invoke.
  */
  removeObserver: function(key, target, method) {
    removeObserver(this, key, target, method);
  },

  /**
    Returns `true` if the object currently has observers registered for a
    particular key. You can use this method to potentially defer performing
    an expensive action until someone begins observing a particular property
    on the object.

    @method hasObserverFor
    @param {String} key Key to check
    @return {Boolean}
  */
  hasObserverFor: function(key) {
    return hasListeners(this, key+':change');
  },

  /**
    Retrieves the value of a property, or a default value in the case that the
    property returns `undefined`.

    ```javascript
    person.getWithDefault('lastName', 'Doe');
    ```

    @method getWithDefault
    @param {String} keyName The name of the property to retrieve
    @param {Object} defaultValue The value to return if the property value is undefined
    @return {Object} The property value or the defaultValue.
  */
  getWithDefault: function(keyName, defaultValue) {
    return getWithDefault(this, keyName, defaultValue);
  },

  /**
    Set the value of a property to the current value plus some amount.

    ```javascript
    person.incrementProperty('age');
    team.incrementProperty('score', 2);
    ```

    @method incrementProperty
    @param {String} keyName The name of the property to increment
    @param {Number} increment The amount to increment by. Defaults to 1
    @return {Number} The new property value
  */
  incrementProperty: function(keyName, increment) {
    if (isNone(increment)) { increment = 1; }
    Ember.assert("Must pass a numeric value to incrementProperty", (!isNaN(parseFloat(increment)) && isFinite(increment)));
    set(this, keyName, (parseFloat(get(this, keyName)) || 0) + increment);
    return get(this, keyName);
  },

  /**
    Set the value of a property to the current value minus some amount.

    ```javascript
    player.decrementProperty('lives');
    orc.decrementProperty('health', 5);
    ```

    @method decrementProperty
    @param {String} keyName The name of the property to decrement
    @param {Number} decrement The amount to decrement by. Defaults to 1
    @return {Number} The new property value
  */
  decrementProperty: function(keyName, decrement) {
    if (isNone(decrement)) { decrement = 1; }
    Ember.assert("Must pass a numeric value to decrementProperty", (!isNaN(parseFloat(decrement)) && isFinite(decrement)));
    set(this, keyName, (get(this, keyName) || 0) - decrement);
    return get(this, keyName);
  },

  /**
    Set the value of a boolean property to the opposite of it's
    current value.

    ```javascript
    starship.toggleProperty('warpDriveEngaged');
    ```

    @method toggleProperty
    @param {String} keyName The name of the property to toggle
    @return {Object} The new property value
  */
  toggleProperty: function(keyName) {
    set(this, keyName, !get(this, keyName));
    return get(this, keyName);
  },

  /**
    Returns the cached value of a computed property, if it exists.
    This allows you to inspect the value of a computed property
    without accidentally invoking it if it is intended to be
    generated lazily.

    @method cacheFor
    @param {String} keyName
    @return {Object} The cached value of the computed property, if any
  */
  cacheFor: function(keyName) {
    return cacheFor(this, keyName);
  },

  // intended for debugging purposes
  observersForKey: function(keyName) {
    return observersFor(this, keyName);
  }
});

export default Observable;
<|endoftext|>


<commit_before>
(function() {

  $.keyframe = $.extend($.keyframe, {

    pathfinderOpts: {
      bezierSteps: 100,
      circleSteps: 100
    },

    bezierPath: function(kfro, p1, p2, p3, p4){

      var opts = $.keyframe.pathfinderOpts;
      if(p4 == null){
        p4 = p1;
      }

      p1 = coord(p1[0],p1[1]);
      p2 = coord(p2[0],p2[1]);
      p3 = coord(p3[0],p3[1]);
      p4 = coord(p4[0],p4[1]);

      var points = {};
      var step = 1 / opts.bezierSteps;

      for (var i = 0; i <= 1.01; i += step){
        var newpos = getBezier(i, p1, p4, p3, p2);
        points[ (100 - Math.round(i * 100)) + '%' ] = { 'transform': 'translate(' + newpos.x + 'px,' + newpos.y + 'px)' };
      }

      return $.extend(kfro, points);

    },

    circlePath: function(kfro, center, radius){
      var opts = $.keyframe.pathfinderOpts;

      center = coord(center[0],center[1]);
      var points = {};
      var pieandahalf = 1.5 * Math.PI;
      var notmuchpie = Math.PI / 180;
      var step = 100 / opts.circleSteps;
      var degreestep = 360 / opts.circleSteps;

      for (var i = 0; i <= opts.circleSteps; ++i){
        var degree = degreestep * i;
        var radians = pieandahalf + degree * notmuchpie;
        var newpos = getCirclePoint(radians, radius, center);
        points[ Math.round(step * i) + '%' ] = { 'transform': 'translate(' + newpos.x + 'px,' + newpos.y + 'px)' };
      }
      return $.extend(kfro, points);
    }
  });

  function getCirclePoint(radians, radius, center) {
    return {
        x: (center.x + radius * Math.cos(radians)),
        y: (center.y + radius * Math.sin(radians))
    }
  }

  //====================================\\
  // 13thParallel.org Beziér Curve Code \\
  //   by Dan Pupius (www.pupius.net)   \\
  //====================================\\

  var coord = function (x,y) {
    if(!x) var x=0;
    if(!y) var y=0;
    return {x: x, y: y};
  }

  function B1(t) { return t*t*t }
  function B2(t) { return 3*t*t*(1-t) }
  function B3(t) { return 3*t*(1-t)*(1-t) }
  function B4(t) { return (1-t)*(1-t)*(1-t) }

  function getBezier(percent,C1,C2,C3,C4) {
    var pos = new coord();
    pos.x = C1.x*B1(percent) + C2.x*B2(percent) + C3.x*B3(percent) + C4.x*B4(percent);
    pos.y = C1.y*B1(percent) + C2.y*B2(percent) + C3.y*B3(percent) + C4.y*B4(percent);
    return pos;
  }

}).call(this);<commit_msg>join multiple transforms<commit_after>
(function() {

  $.keyframe = $.extend($.keyframe, {

    pathfinderOpts: {
      bezierSteps: 100,
      circleSteps: 100
    },

    bezierPath: function(kfro, p1, p2, p3, p4){

      var opts = $.keyframe.pathfinderOpts;
      if(p4 == null){
        p4 = p1;
      }

      p1 = coord(p1[0],p1[1]);
      p2 = coord(p2[0],p2[1]);
      p3 = coord(p3[0],p3[1]);
      p4 = coord(p4[0],p4[1]);

      var points = {};
      var step = 1 / opts.bezierSteps;

      for (var i = 0; i <= 1.01; i += step){
        var newpos = getBezier(i, p1, p4, p3, p2);
        points[ (100 - Math.round(i * 100)) + '%' ] = { 'transform': 'translate(' + newpos.x + 'px,' + newpos.y + 'px)' };
      }

      return $.extend(kfro, points);

    },

    circlePath: function(kfro, center, radius){
      var opts = $.keyframe.pathfinderOpts;

      center = coord(center[0],center[1]);
      var points = {};
      var pieandahalf = 1.5 * Math.PI;
      var notmuchpie = Math.PI / 180;
      var step = 100 / opts.circleSteps;
      var degreestep = 360 / opts.circleSteps;

      for (var i = 0; i <= opts.circleSteps; ++i){
        var degree = degreestep * i;
        var radians = pieandahalf + degree * notmuchpie;
        var newpos = getCirclePoint(radians, radius, center);
        points[ Math.round(step * i) + '%' ] = { 'transform': 'translate(' + newpos.x + 'px,' + newpos.y + 'px)' };
      }

      for(step in kfro){
        var rules = kfro[step];
        for(newstep in points){
          var newrules = points[newstep];
          if(step == newstep){
            if(newrules.transform && rules.transform){
              points[newstep].transform = newrules.transform + ' ' + rules.transform;
              break;
            }
          }
        }
      }

      return $.extend(kfro, points);
    }
  });

  function getCirclePoint(radians, radius, center) {
    return {
        x: (center.x + radius * Math.cos(radians)),
        y: (center.y + radius * Math.sin(radians))
    }
  }

  //====================================\\
  // 13thParallel.org Beziér Curve Code \\
  //   by Dan Pupius (www.pupius.net)   \\
  //====================================\\

  var coord = function (x,y) {
    if(!x) var x=0;
    if(!y) var y=0;
    return {x: x, y: y};
  }

  function B1(t) { return t*t*t }
  function B2(t) { return 3*t*t*(1-t) }
  function B3(t) { return 3*t*(1-t)*(1-t) }
  function B4(t) { return (1-t)*(1-t)*(1-t) }

  function getBezier(percent,C1,C2,C3,C4) {
    var pos = new coord();
    pos.x = C1.x*B1(percent) + C2.x*B2(percent) + C3.x*B3(percent) + C4.x*B4(percent);
    pos.y = C1.y*B1(percent) + C2.y*B2(percent) + C3.y*B3(percent) + C4.y*B4(percent);
    return pos;
  }

}).call(this);<|endoftext|>


<commit_before>let config = require('./commands/pen');
let retriveLocalFile = require('./helpers/retrive-local-file')

class TurtleGraphic {
	constructor(path) {
		this.file = retriveLocalFile(path);
	}
}

let graphics = new TurtleGraphic('.draw');<commit_msg>Adding DOM and validation check.<commit_after>let config = require('./commands/pen');
let retriveLocalFile = require('./helpers/retrive-local-file');
let Validator = require('./validator');

class TurtleGraphic {
	constructor(options) {
		if(!Validator.options) return false;

		this.file = retriveLocalFile(options.path);
		this.canvas = options.canvas;
	}
}

document.addEventListener("DOMContentLoaded", function(event) {
	let graphics = new TurtleGraphic({
		path: '.draw'
		canvas: document.querySelectorAll('canvas')
	});
}
<|endoftext|>


<commit_before>'use strict'

const nfs = require('./nice-fs')
const object = require('./object')
const index = require('./index')
const tree = require('./tree')
const commit = require('./commit')
const utils = require('./utils')
const remote = require('./remote')

const headFile = '.ndr/HEAD'

Error.stackTraceLimit = Infinity

function init () {
	nfs.mkdir('.ndr')

	nfs.mkdir('.ndr/objects')
	nfs.mkdir('.ndr/refs')

	nfs.writeJson(headFile, { type: 'ref', ref: 'refs/master' })
}

function add (file) {
	const contents = nfs.read(file)
	const hash = object.storeBlob(contents)
	index.add(file, hash)
}

function catFile (type, hash) {
	console.log({
		blob: object.retrieveBlob,
		tree: object.retrieveTree,
		commit: object.retrieveCommit,
	}[type](hash))
}

function commitInitial (message) {
	const indexValue = index.retrieve()
	const treeHash = tree.store(indexValue)

	const commitHash = commit.store(message, treeHash, null)

	const head = nfs.readJson(headFile)

	nfs.write(`.ndr/${head.ref}`, commitHash)
}

function commitNoninitial (message) {
	const indexValue = index.retrieve()

	const candidateTreeHash = tree.store(indexValue)

	const head = nfs.readJson(headFile)

	const commitHash = head.type === 'ref'
		? nfs.read(`.ndr/${head.ref}`)
		: head.hash

	const commitObject = commit.retrieve(commitHash)

	const currentTreeHash = commitObject.tree

	if (candidateTreeHash === currentTreeHash) {
		console.log('nothing to commit')
		return
	}

	const newCommitHash = commit.store(message, candidateTreeHash, commitHash)

	if (head.type === 'ref') {
		nfs.write(`.ndr/${head.ref}`, newCommitHash)
	} else {
		nfs.writeJson(headFile, { type: 'hash', hash: newCommitHash })
	}
}

function commitCommand (message) {
	const head = nfs.readJson(headFile)

	if (head.type === 'ref' && !nfs.exists(`.ndr/${head.ref}`)) {
		commitInitial(message)
	} else {
		commitNoninitial(message)
	}
}

function log () {
	const head = nfs.readJson(headFile)

	if (head.type === 'ref' && !nfs.exists(`.ndr/${head.ref}`)) {
		console.log('your branch does not have any commits yet')
		return
	}

	function traverse (commitHash) {
		const commitObject = commit.retrieve(commitHash)

		console.log(
			commitHash.slice(0, 7),
			commitHash,
			commitObject.message
		)

		if (commitObject.parent) {
			traverse(commitObject.parent)
		}
	}

	const commitHash = head.type === 'ref'
		? nfs.read(`.ndr/${head.ref}`)
		: head.hash

	traverse(commitHash)
}

function branch (name) {
	const head = nfs.readJson(headFile)

	const commitHash = head.type === 'ref'
		? nfs.read(`.ndr/${head.ref}`)
		: head.hash

	nfs.write(`.ndr/refs/${name}`, commitHash)
}

function branchList () {
	const head = nfs.readJson(headFile)
	const headBranch = head.type !== 'ref'
		? null
		: head.ref.match(/\/(\w+)$/)[1]

	const branches = nfs.readdir(`.ndr/refs`)

	branches.forEach((branch) => {
		console.log(headBranch === branch ? '*' : ' ', branch)
	})
}

function checkout (hashOrBranch) {
	const isHash = /[\da-f]{7}/.test(hashOrBranch)

	const commitHash = isHash
		? hashOrBranch
		: nfs.read(`.ndr/refs/${hashOrBranch}`)

	const commitObject = commit.retrieve(commitHash)

	tree.retrieve(commitObject.tree)

	index.updateFromTree(commitObject.tree)

	if (isHash) {
		nfs.writeJson(headFile, { type: 'hash', hash: commitHash })
	} else {
		nfs.writeJson(headFile, { type: 'ref', ref: `refs/${hashOrBranch}` })
	}
}

function delta (ancestorHash, descendantHash) {
	const objects = utils.computeDelta(ancestorHash, descendantHash)

	objects.forEach((hash) => {
		console.log(hash)
	})
}

function push (url) {
	remote.push(url)
}

module.exports = {
	init,
	add,
	commit: commitCommand,
	log,
	branch,
	branchList,
	checkout,
	catFile,
	delta,
	push,
}<commit_msg>Refactor out common logic<commit_after>'use strict'

const nfs = require('./nice-fs')
const object = require('./object')
const index = require('./index')
const tree = require('./tree')
const commit = require('./commit')
const utils = require('./utils')
const remote = require('./remote')

const headFile = '.ndr/HEAD'

Error.stackTraceLimit = Infinity

function init () {
	nfs.mkdir('.ndr')

	nfs.mkdir('.ndr/objects')
	nfs.mkdir('.ndr/refs')

	nfs.writeJson(headFile, { type: 'ref', ref: 'refs/master' })
}

function add (file) {
	const contents = nfs.read(file)
	const hash = object.storeBlob(contents)
	index.add(file, hash)
}

function catFile (type, hash) {
	console.log({
		blob: object.retrieveBlob,
		tree: object.retrieveTree,
		commit: object.retrieveCommit,
	}[type](hash))
}

function commitInitial (message) {
	const indexValue = index.retrieve()
	const treeHash = tree.store(indexValue)

	const commitHash = commit.store(message, treeHash, null)

	const head = nfs.readJson(headFile)

	nfs.write(`.ndr/${head.ref}`, commitHash)
}

function getHeadHash (head) {
	return head.type === 'ref'
		? nfs.read(`.ndr/${head.ref}`)
		: head.hash
}

function commitNoninitial (message) {
	const indexValue = index.retrieve()

	const candidateTreeHash = tree.store(indexValue)

	const head = nfs.readJson(headFile)

	const commitHash = getHeadHash(head)

	const commitObject = commit.retrieve(commitHash)

	const currentTreeHash = commitObject.tree

	if (candidateTreeHash === currentTreeHash) {
		console.log('nothing to commit')
		return
	}

	const newCommitHash = commit.store(message, candidateTreeHash, commitHash)

	if (head.type === 'ref') {
		nfs.write(`.ndr/${head.ref}`, newCommitHash)
	} else {
		nfs.writeJson(headFile, { type: 'hash', hash: newCommitHash })
	}
}

function commitCommand (message) {
	const head = nfs.readJson(headFile)

	if (head.type === 'ref' && !nfs.exists(`.ndr/${head.ref}`)) {
		commitInitial(message)
	} else {
		commitNoninitial(message)
	}
}

function log () {
	const head = nfs.readJson(headFile)

	if (head.type === 'ref' && !nfs.exists(`.ndr/${head.ref}`)) {
		console.log('your branch does not have any commits yet')
		return
	}

	function traverse (commitHash) {
		const commitObject = commit.retrieve(commitHash)

		console.log(
			commitHash.slice(0, 7),
			commitHash,
			commitObject.message
		)

		if (commitObject.parent) {
			traverse(commitObject.parent)
		}
	}

	const commitHash = getHeadHash(head)

	traverse(commitHash)
}

function branch (name) {
	const head = nfs.readJson(headFile)

	const commitHash = getHeadHash(head)

	nfs.write(`.ndr/refs/${name}`, commitHash)
}

function branchList () {
	const head = nfs.readJson(headFile)
	const headBranch = head.type !== 'ref'
		? null
		: head.ref.match(/\/(\w+)$/)[1]

	const branches = nfs.readdir(`.ndr/refs`)

	branches.forEach((branch) => {
		console.log(headBranch === branch ? '*' : ' ', branch)
	})
}

function checkout (hashOrBranch) {
	const isHash = /[\da-f]{7}/.test(hashOrBranch)

	const commitHash = isHash
		? hashOrBranch
		: nfs.read(`.ndr/refs/${hashOrBranch}`)

	const commitObject = commit.retrieve(commitHash)

	tree.retrieve(commitObject.tree)

	index.updateFromTree(commitObject.tree)

	if (isHash) {
		nfs.writeJson(headFile, { type: 'hash', hash: commitHash })
	} else {
		nfs.writeJson(headFile, { type: 'ref', ref: `refs/${hashOrBranch}` })
	}
}

function delta (ancestorHash, descendantHash) {
	const objects = utils.computeDelta(ancestorHash, descendantHash)

	objects.forEach((hash) => {
		console.log(hash)
	})
}

function push (url) {
	remote.push(url)
}

module.exports = {
	init,
	add,
	commit: commitCommand,
	log,
	branch,
	branchList,
	checkout,
	catFile,
	delta,
	push,
}<|endoftext|>