<commit_before>/*
 * We have a few competing goals:
 *
 * First, be as responsive as possible.  Preload nearby post HTML and their images.
 *
 * If data in a post page changes, eg. if the user votes, then coming back to the page
 * later should retain the changes.  This means either requesting the page again, or
 * retaining the document node and reusing it, so we preserve the changes that were
 * made in-place.
 *
 * Don't use too much memory.  If we keep every document node in memory as we use it,
 * the images will probably be kept around too.  Release older nodes, so the browser
 * is more likely to release images that havn't been used in a while.
 *
 * We do the following:
 * - When we load a new post, it's formatted and its scripts are evaluated normally.
 * - When we're replacing the displayed post, its node is stashed away in a node cache.
 * - If we come back to the post while it's in the node cache, we'll use the node directly.
 * - HTML and images for posts are preloaded.  We don't use a simple mechanism like
 *   Preload.preload_raw, because Opera's caching is broken for XHR and it'll always
 *   do a slow revalidation.
 * - We don't depend on browser caching for HTML.  That would require us to expire a
 *   page when we switch away from it if we've made any changes (eg. voting), so we
 *   don't pull an out-of-date page next time.  This is slower, and would require us
 *   to be careful about expiring the cache.
 */
PoolBrowser = function(pool, pool_posts)
{
  this.pool = pool;
  this.pool_id = pool.id;
  this.pool_posts = pool_posts;
  this.current_post_id = null;
  this.cache_session_id = (new Date()).valueOf();
  this.post_node_cache = new Hash;
  this.post_html_cache = new Hash;
  this.html_preloads = new Hash;

  Post.observe_finished_loading(this.displayed_image_finished_loading.bind(this));

  this.set_post(this.get_current_post_id());

  OnKey(65, { AlwaysAllowOpera: true }, function(e) { this.move(false); }.bind(this));
  OnKey(83, { AlwaysAllowOpera: true }, function(e) { this.move(true); }.bind(this));

  Element.observe(window, "hashchange", function(e) {
    this.set_post(this.get_current_post_id(), this.pool_id);
  }.bind(this));
}

PoolBrowser.prototype.get_first_post_id = function()
{
  return this.pool_posts[0].post_id;
}

PoolBrowser.prototype.get_current_post_id = function()
{
  var hash = document.location.hash;
  if(!hash)
    return this.get_first_post_id();
  hash = hash.substr(1);

  return parseInt(hash);
}

PoolBrowser.prototype.find_post_idx_in_pool = function(post_id)
{
  for(var i = 0; i < this.pool_posts.length; ++i)
  {
    if(this.pool_posts[i].post_id == post_id)
      return i;
  }
  return -1;
}

PoolBrowser.prototype.find_post_in_pool = function(post_id)
{
  var idx = this.find_post_idx_in_pool(post_id);
  if(idx == -1)
    return null;
  return this.pool_posts[idx];
}

PoolBrowser.prototype.displayed_image_finished_loading = function(success, event)
{
  /*
   * The image in the post we're displaying is finished loading.
   *
   * Preload the next and previous posts.  Normally, one or the other of these will
   * already be in cache.
   */
  var post_id = this.current_post_id;
  var pool_post = this.find_post_in_pool(post_id);
  var post_ids_to_preload = [];
  var adjacent_pool_post = this.get_adjacent_post_id_wrapped(pool_post, true);
  if(adjacent_pool_post != null)
    post_ids_to_preload.push(adjacent_pool_post);
  var adjacent_pool_post = this.get_adjacent_post_id_wrapped(pool_post, false);
  if(adjacent_pool_post != null)
    post_ids_to_preload.push(adjacent_pool_post);
  this.preload(post_ids_to_preload);
}

/* If post_id isn't cached and isn't already being loaded, start loading it. */
PoolBrowser.prototype.load_post_html = function(post_id)
{
  /* If the post's node is cached, then there's never any reason to load its HTML again. */
  if(this.post_node_cache.get(post_id))
    return;

  var data = this.post_html_cache.get(post_id);
  if(data != null)
  {
    /* This post's HTML is already loaded. */
    if(this.current_post_id == post_id)
    {
      this.post_html_cache.unset(post_id);
      this.set_post_content(data, post_id);
    }
    return;
  }

  var existing_request = this.html_preloads.get(post_id);
  if(existing_request != null)
  {
    /* This post is already being loaded. */
    return;
  }

  var url = this.get_url_for_post_page(post_id);
  var request = new Ajax.Request(url, {
    method: "get",
    evalJSON: false,
    evalJS: false,
    parameters: null,
    onComplete: function(resp)
    {
      this.html_preloads.unset(post_id);
    }.bind(this),
    onSuccess: function(resp)
    {
      resp = resp.responseText;

      /* If this is the post that currently wants to be displayed, switch to it. */
      if(this.current_post_id == post_id)
      {
        this.set_post_content(resp, post_id);
        return;
      }

      /* Otherwise, just cache the data for later. */
      this.post_html_cache.set(post_id, resp);
    }.bind(this),
    onFailure: function(resp)
    {
      if(parseInt(this.current_post_id) == parseInt(post_id))
      {
        /* The post the user wants to see failed to load. */
        notice("Error "  + resp.status + " loading post");
      }
    }.bind(this)
  });

  this.html_preloads.set(post_id, request);
}

/* Begin preloading the HTML and images for the given post IDs. */
PoolBrowser.prototype.preload = function(post_ids)
{
  var new_preload_container = Preload.create_preload_container();
  for(var i = 0; i < post_ids.length; ++i)
  {
    var post_id = post_ids[i];

    this.load_post_html(post_id);

    var post = Post.posts.get(post_id);
    new_preload_container.preload(post.sample_url);
  }

  /* If we already were preloading images, we created the new preloads before
   * deleting the old ones.  That way, any images that are still being preloaded
   * won't be deleted and recreated, possibly causing the download to be interrupted
   * and resumed. */
  if(this.preload_container)
    this.preload_container.destroy();
  this.preload_container = new_preload_container;
}

PoolBrowser.prototype.clear_container = function()
{
  var content = $("post-content");
  var old_container = content.down(".post-content-container");
  if(!old_container)
    return;

  /* We're no longer displaying the post, but we'll keep a reference to the container
   * in post_node_cache.  Clear the image source attribute, to help hint the browser that
   * we don't need to keep the image around.  We'll restore it if we display the post
   * again. */
  var img = old_container.down("#image");
  img.saved_src = img.src;
  img.src = "about:blank";
  content.removeChild(old_container);
}

PoolBrowser.prototype.set_post_content = function(data, post_id)
{
  /* Clear the previous post, if any. */
  this.clear_container();

  var content = $("post-content");

  if(typeof(data) == typeof "")
  {
    /* The argument is a string, so it's a new, raw block of HTML.  We need to create
     * its node. */
    var post_content_container = $(document.createElement("DIV"));
    post_content_container.className = "post-content-container";

    content.appendChild(post_content_container);

    /* This is like post_content_container.update(data), but we don't defer scripts, since
     * that breaks things (eg. resized_notice gets moved around later, after we've already
     * aligned the viewport). */
    post_content_container.innerHTML = data.stripScripts();
    data.evalScripts(data);

    InitTextAreas();

    this.post_node_cache.set(post_id, post_content_container);
  }
  else
  {
    /* The argument is the node that we created previously.  Just insert it. */
    var img = data.down(".image");
    img.src = img.saved_src;

    content.appendChild(data);
  }

  Post.scale_and_fit_image();
  document.location.hash = post_id;

  var title = "";
  title = this.pool.name.replace(/_/g, " ");

  var idx = this.find_post_idx_in_pool(post_id);
  if(idx != -1)
  {
    var sequence = this.pool_posts[idx].sequence;
    title += " ";
    if(sequence.match(/^[0-9]/))
      title += "#";
    title += sequence;
  }

  document.title = title;
  Post.init_post_show(post_id);
}

PoolBrowser.prototype.get_url_for_post_page = function(post_id)
{
  var cache_id = this.cache_session_id + "-" + post_id;
  var url = "/post/show/" + post_id + "?browse_pool_id=" + this.pool_id + "&cache=" + cache_id;
  return url;
}

PoolBrowser.prototype.set_post = function(post_id)
{
  /* If the post isn't in the pool, pick a default. */
  if(this.find_post_in_pool(post_id) == null)
    post_id = this.get_first_post_id();

  if(this.current_post_id == post_id)
    return;
  this.current_post_id = post_id;

  var post_content_container = this.post_node_cache.get(post_id);
  if(post_content_container)
  {
    this.set_post_content(post_content_container, post_id);
    return;
  }

  /* We don't have the node cached.  Open the page from HTML cache or start
   * loading the page as necessary. */
  this.load_post_html(post_id);
}

/* If first is true, return the first pool_post in the pool, otherwise return the last pool_post. */
PoolBrowser.prototype.get_boundary_pool_post = function(first)
{
  if(first)
    return this.pool_posts[0];
  else
    return this.pool_posts[this.pool_posts.length-1];
}

/* If next is true, return the post after the given pool_post, otherwise return
 * the post before it. */
PoolBrowser.prototype.get_adjacent_post_id = function(pool_post, next)
{
  if(next)
    return pool_post.next_post_id;
  else
    return pool_post.prev_post_id;
}

/* Return the next or previous post, wrapping around if necessary. */
PoolBrowser.prototype.get_adjacent_post_id_wrapped = function(pool_post, next)
{
  var adjacent_pool_post_id = this.get_adjacent_post_id(pool_post, next);
  if(adjacent_pool_post_id != null)
    return adjacent_pool_post_id;
  return this.get_boundary_pool_post(next).post_id;
}

/* Change to the next or previous post in the pool. */
PoolBrowser.prototype.move = function(next)
{
  var pool_post = this.find_post_in_pool(this.get_current_post_id());
  var key = next? "next_post_id":"prev_post_id";
  var new_post_id = this.get_adjacent_post_id(pool_post, next); //pool_post[key];
  if(new_post_id == null)
  {
    if(next)
      notice("Starting over from the beginning");
    else
      notice("Continued from the end");
    new_post_id = this.get_boundary_pool_post(next).post_id;
  }

  this.set_post(new_post_id, this.pool_id);
}

<commit_msg>remove extra post id from url<commit_after>/*
 * We have a few competing goals:
 *
 * First, be as responsive as possible.  Preload nearby post HTML and their images.
 *
 * If data in a post page changes, eg. if the user votes, then coming back to the page
 * later should retain the changes.  This means either requesting the page again, or
 * retaining the document node and reusing it, so we preserve the changes that were
 * made in-place.
 *
 * Don't use too much memory.  If we keep every document node in memory as we use it,
 * the images will probably be kept around too.  Release older nodes, so the browser
 * is more likely to release images that havn't been used in a while.
 *
 * We do the following:
 * - When we load a new post, it's formatted and its scripts are evaluated normally.
 * - When we're replacing the displayed post, its node is stashed away in a node cache.
 * - If we come back to the post while it's in the node cache, we'll use the node directly.
 * - HTML and images for posts are preloaded.  We don't use a simple mechanism like
 *   Preload.preload_raw, because Opera's caching is broken for XHR and it'll always
 *   do a slow revalidation.
 * - We don't depend on browser caching for HTML.  That would require us to expire a
 *   page when we switch away from it if we've made any changes (eg. voting), so we
 *   don't pull an out-of-date page next time.  This is slower, and would require us
 *   to be careful about expiring the cache.
 */
PoolBrowser = function(pool, pool_posts)
{
  this.pool = pool;
  this.pool_id = pool.id;
  this.pool_posts = pool_posts;
  this.current_post_id = null;
  this.cache_session_id = (new Date()).valueOf();
  this.post_node_cache = new Hash;
  this.post_html_cache = new Hash;
  this.html_preloads = new Hash;

  Post.observe_finished_loading(this.displayed_image_finished_loading.bind(this));

  this.set_post(this.get_current_post_id());

  OnKey(65, { AlwaysAllowOpera: true }, function(e) { this.move(false); }.bind(this));
  OnKey(83, { AlwaysAllowOpera: true }, function(e) { this.move(true); }.bind(this));

  Element.observe(window, "hashchange", function(e) {
    this.set_post(this.get_current_post_id(), this.pool_id);
  }.bind(this));
}

PoolBrowser.prototype.get_first_post_id = function()
{
  return this.pool_posts[0].post_id;
}

PoolBrowser.prototype.get_current_post_id = function()
{
  var hash = document.location.hash;
  if(!hash)
    return this.get_first_post_id();
  hash = hash.substr(1);

  return parseInt(hash);
}

PoolBrowser.prototype.find_post_idx_in_pool = function(post_id)
{
  for(var i = 0; i < this.pool_posts.length; ++i)
  {
    if(this.pool_posts[i].post_id == post_id)
      return i;
  }
  return -1;
}

PoolBrowser.prototype.find_post_in_pool = function(post_id)
{
  var idx = this.find_post_idx_in_pool(post_id);
  if(idx == -1)
    return null;
  return this.pool_posts[idx];
}

PoolBrowser.prototype.displayed_image_finished_loading = function(success, event)
{
  /*
   * The image in the post we're displaying is finished loading.
   *
   * Preload the next and previous posts.  Normally, one or the other of these will
   * already be in cache.
   */
  var post_id = this.current_post_id;
  var pool_post = this.find_post_in_pool(post_id);
  var post_ids_to_preload = [];
  var adjacent_pool_post = this.get_adjacent_post_id_wrapped(pool_post, true);
  if(adjacent_pool_post != null)
    post_ids_to_preload.push(adjacent_pool_post);
  var adjacent_pool_post = this.get_adjacent_post_id_wrapped(pool_post, false);
  if(adjacent_pool_post != null)
    post_ids_to_preload.push(adjacent_pool_post);
  this.preload(post_ids_to_preload);
}

/* If post_id isn't cached and isn't already being loaded, start loading it. */
PoolBrowser.prototype.load_post_html = function(post_id)
{
  /* If the post's node is cached, then there's never any reason to load its HTML again. */
  if(this.post_node_cache.get(post_id))
    return;

  var data = this.post_html_cache.get(post_id);
  if(data != null)
  {
    /* This post's HTML is already loaded. */
    if(this.current_post_id == post_id)
    {
      this.post_html_cache.unset(post_id);
      this.set_post_content(data, post_id);
    }
    return;
  }

  var existing_request = this.html_preloads.get(post_id);
  if(existing_request != null)
  {
    /* This post is already being loaded. */
    return;
  }

  var url = this.get_url_for_post_page(post_id);
  var request = new Ajax.Request(url, {
    method: "get",
    evalJSON: false,
    evalJS: false,
    parameters: null,
    onComplete: function(resp)
    {
      this.html_preloads.unset(post_id);
    }.bind(this),
    onSuccess: function(resp)
    {
      resp = resp.responseText;

      /* If this is the post that currently wants to be displayed, switch to it. */
      if(this.current_post_id == post_id)
      {
        this.set_post_content(resp, post_id);
        return;
      }

      /* Otherwise, just cache the data for later. */
      this.post_html_cache.set(post_id, resp);
    }.bind(this),
    onFailure: function(resp)
    {
      if(parseInt(this.current_post_id) == parseInt(post_id))
      {
        /* The post the user wants to see failed to load. */
        notice("Error "  + resp.status + " loading post");
      }
    }.bind(this)
  });

  this.html_preloads.set(post_id, request);
}

/* Begin preloading the HTML and images for the given post IDs. */
PoolBrowser.prototype.preload = function(post_ids)
{
  var new_preload_container = Preload.create_preload_container();
  for(var i = 0; i < post_ids.length; ++i)
  {
    var post_id = post_ids[i];

    this.load_post_html(post_id);

    var post = Post.posts.get(post_id);
    new_preload_container.preload(post.sample_url);
  }

  /* If we already were preloading images, we created the new preloads before
   * deleting the old ones.  That way, any images that are still being preloaded
   * won't be deleted and recreated, possibly causing the download to be interrupted
   * and resumed. */
  if(this.preload_container)
    this.preload_container.destroy();
  this.preload_container = new_preload_container;
}

PoolBrowser.prototype.clear_container = function()
{
  var content = $("post-content");
  var old_container = content.down(".post-content-container");
  if(!old_container)
    return;

  /* We're no longer displaying the post, but we'll keep a reference to the container
   * in post_node_cache.  Clear the image source attribute, to help hint the browser that
   * we don't need to keep the image around.  We'll restore it if we display the post
   * again. */
  var img = old_container.down("#image");
  img.saved_src = img.src;
  img.src = "about:blank";
  content.removeChild(old_container);
}

PoolBrowser.prototype.set_post_content = function(data, post_id)
{
  /* Clear the previous post, if any. */
  this.clear_container();

  var content = $("post-content");

  if(typeof(data) == typeof "")
  {
    /* The argument is a string, so it's a new, raw block of HTML.  We need to create
     * its node. */
    var post_content_container = $(document.createElement("DIV"));
    post_content_container.className = "post-content-container";

    content.appendChild(post_content_container);

    /* This is like post_content_container.update(data), but we don't defer scripts, since
     * that breaks things (eg. resized_notice gets moved around later, after we've already
     * aligned the viewport). */
    post_content_container.innerHTML = data.stripScripts();
    data.evalScripts(data);

    InitTextAreas();

    this.post_node_cache.set(post_id, post_content_container);
  }
  else
  {
    /* The argument is the node that we created previously.  Just insert it. */
    var img = data.down(".image");
    img.src = img.saved_src;

    content.appendChild(data);
  }

  Post.scale_and_fit_image();
  document.location.hash = post_id;

  var title = "";
  title = this.pool.name.replace(/_/g, " ");

  var idx = this.find_post_idx_in_pool(post_id);
  if(idx != -1)
  {
    var sequence = this.pool_posts[idx].sequence;
    title += " ";
    if(sequence.match(/^[0-9]/))
      title += "#";
    title += sequence;
  }

  document.title = title;
  Post.init_post_show(post_id);
}

PoolBrowser.prototype.get_url_for_post_page = function(post_id)
{
  return "/post/show/" + post_id + "?browse_pool_id=" + this.pool_id + "&cache=" + this.cache_session_id;
}

PoolBrowser.prototype.set_post = function(post_id)
{
  /* If the post isn't in the pool, pick a default. */
  if(this.find_post_in_pool(post_id) == null)
    post_id = this.get_first_post_id();

  if(this.current_post_id == post_id)
    return;
  this.current_post_id = post_id;

  var post_content_container = this.post_node_cache.get(post_id);
  if(post_content_container)
  {
    this.set_post_content(post_content_container, post_id);
    return;
  }

  /* We don't have the node cached.  Open the page from HTML cache or start
   * loading the page as necessary. */
  this.load_post_html(post_id);
}

/* If first is true, return the first pool_post in the pool, otherwise return the last pool_post. */
PoolBrowser.prototype.get_boundary_pool_post = function(first)
{
  if(first)
    return this.pool_posts[0];
  else
    return this.pool_posts[this.pool_posts.length-1];
}

/* If next is true, return the post after the given pool_post, otherwise return
 * the post before it. */
PoolBrowser.prototype.get_adjacent_post_id = function(pool_post, next)
{
  if(next)
    return pool_post.next_post_id;
  else
    return pool_post.prev_post_id;
}

/* Return the next or previous post, wrapping around if necessary. */
PoolBrowser.prototype.get_adjacent_post_id_wrapped = function(pool_post, next)
{
  var adjacent_pool_post_id = this.get_adjacent_post_id(pool_post, next);
  if(adjacent_pool_post_id != null)
    return adjacent_pool_post_id;
  return this.get_boundary_pool_post(next).post_id;
}

/* Change to the next or previous post in the pool. */
PoolBrowser.prototype.move = function(next)
{
  var pool_post = this.find_post_in_pool(this.get_current_post_id());
  var key = next? "next_post_id":"prev_post_id";
  var new_post_id = this.get_adjacent_post_id(pool_post, next); //pool_post[key];
  if(new_post_id == null)
  {
    if(next)
      notice("Starting over from the beginning");
    else
      notice("Continued from the end");
    new_post_id = this.get_boundary_pool_post(next).post_id;
  }

  this.set_post(new_post_id, this.pool_id);
}

<|endoftext|>


<commit_before>const serverURL = 'http://glacial-cove-76906.herokuapp.com';

function getVotes(shoutId,cb){
	$.get(serverURL+'/get-votes?shout_id='+shoutId,function(res,status){
		return cb(res,status);
	});
}

function renderButtons(){

	$('.shout-footer > .s-action-list').each(function(){
		var self = this;
		var shoutId = $(this).attr('data-id') ? $(this).attr('data-id') .trim() : '' ;
		var $container = $($(self).closest('.activity-element'));
		//Fabi
		if($container.hasClass('negative-added'))
			return true; //continue

		getVotes(shoutId,function(res,status){
			var button = $(
			`

		 					${res?res.count:'0'}

`);

			$(self).find('div.require-login.button-action-s.action-vote.hastipsy.pointer').before(button);
			//Mark as added - Fabi
			$container.addClass('negative-added');
			button.on('click', function(event){
				event.preventDefault();
				var likes = parseInt(button.find('span.like_count').text());
				button.find('span.like_count').text(likes+1);
				vote(shoutId);
				button.off('click');
			});
		});
	});

	$('.list-main-actions').each(function(){
		var self = this;
		var shoutId = $(this).find('.shout-action-like').attr('data-id').trim();
		var $container = $($(self).closest('.shout-item'));
		//Fabi
		if($container.hasClass('negative-added'))
			return true; //continue
		getVotes(shoutId,function(res,status){
			var button = $(
			`

					${res?res.count:'0'}

`);
			//Mark as added - Fabi
			$container.addClass('negative-added');
			$(self).append(button);
			button.on('click', function(event){
				event.preventDefault();
				var likes = parseInt(button.find('span.like_count').text());
				button.find('span.like_count').text(likes+1);
				vote(shoutId);
				button.off('click');
			});
		});
	})

	$('article.shoutsb').each(function(){
		var self = this;
		var shoutId = $(this).attr('data-id') ? $(this).attr('data-id') .trim() : '' ;
		getVotes(shoutId,function(res,status){
			var button = $(
			`

					${res?res.count:'0'}

			`);
			$(self).find('.like.shoutsb__like.icon-pulgararriba').after(button);
			button.on('click', function(event){
				event.preventDefault();
				var likes = parseInt(button.find('span.like_count').text());
				button.find('span.like_count').text(likes+1);
				vote(shoutId);
				button.off('click');
			});
		});
	});

}

function vote(shoutId){

	var avatarUrl = '';
	var user_id = '';
	var nick = $('.user-name').text().trim();

	$.get('http://api.taringa.net/user/nick/view/'+nick,function(res,status){
		user_id = res.id;
		avatarUrl=res.avatar? res.avatar.medium:'';
		$.post(serverURL+'/vote',{
			shout_id:shoutId,
			avatarUrl:avatarUrl,
			nick:nick,
			user_id:user_id
		},function(res,status){
			console.log(res,status);
		});
	})
}

$(document).ready(function(){
	//Stylesheet
	var Stylesheet =".button-action-s.no-me-gusta .action-number{float:right;} .button-action-s.no-me-gusta .icon-pulgarabajo{float:left;margin:2px 11px;margin-right:2px;} ";
	$('head').append('');
	renderButtons();
});

//Fabi
if(window.location.pathname ==='/mi'){
	// /mi
	$('#Feed-list').onResize().on('resize',function(event){
		renderButtons();
	});
}else{
	//shouts
	$('.shouts-list').onResize().on('resize',function(event){
		renderButtons();
	});
}<commit_msg>Fix bug duplicated buttons<commit_after>const serverURL = 'http://glacial-cove-76906.herokuapp.com';

function getVotes(shoutId,cb){
	$.get(serverURL+'/get-votes?shout_id='+shoutId,function(res,status){
		return cb(res,status);
	});
}

function renderButtons(){

	$('.shout-footer > .s-action-list').each(function(){
		var self = this;
		var shoutId = $(this).attr('data-id') ? $(this).attr('data-id') .trim() : '' ;
		var $container = $($(self).closest('.activity-element'));
		//Fabi
		if($container.hasClass('negative-added'))
			return true; //continue

		var button = $(
			`

`);

		$(self).find('div.require-login.button-action-s.action-vote.hastipsy.pointer').before(button);
		//Mark as added - Fabi
		$container.addClass('negative-added');

		getVotes(shoutId,function(res,status){
			button.find('span.like_count').text(res?res.count:'0');
			button.on('click', function(event){
				event.preventDefault();
				var likes = parseInt(button.find('span.like_count').text());
				button.find('span.like_count').text(likes+1);
				vote(shoutId);
				button.off('click');
			});
		});
	});

	$('.list-main-actions').each(function(){
		var self = this;
		var shoutId = $(this).find('.shout-action-like').attr('data-id').trim();
		var $container = $($(self).closest('.shout-item'));
		//Fabi
		if($container.hasClass('negative-added'))
			return true; //continue

		var button = $(
			`

`);
		//Mark as added - Fabi
		$container.addClass('negative-added');
		$(self).append(button);

		getVotes(shoutId,function(res,status){
			button.find('span.like_count').text(res?res.count:'0');
			button.on('click', function(event){
				event.preventDefault();
				var likes = parseInt(button.find('span.like_count').text());
				button.find('span.like_count').text(likes+1);
				vote(shoutId);
				button.off('click');
			});
		});
	})

	$('article.shoutsb').each(function(){
		var self = this;
		var shoutId = $(this).attr('data-id') ? $(this).attr('data-id') .trim() : '' ;
		getVotes(shoutId,function(res,status){
			var button = $(
			`

					${res?res.count:'0'}

			`);
			$(self).find('.like.shoutsb__like.icon-pulgararriba').after(button);
			button.on('click', function(event){
				event.preventDefault();
				var likes = parseInt(button.find('span.like_count').text());
				button.find('span.like_count').text(likes+1);
				vote(shoutId);
				button.off('click');
			});
		});
	});

}

function vote(shoutId){

	var avatarUrl = '';
	var user_id = '';
	var nick = $('.user-name').text().trim();

	$.get('http://api.taringa.net/user/nick/view/'+nick,function(res,status){
		user_id = res.id;
		avatarUrl=res.avatar? res.avatar.medium:'';
		$.post(serverURL+'/vote',{
			shout_id:shoutId,
			avatarUrl:avatarUrl,
			nick:nick,
			user_id:user_id
		},function(res,status){
			console.log(res,status);
		});
	})
}

$(document).ready(function(){
	//Stylesheet
	var Stylesheet =".button-action-s.no-me-gusta .action-number{float:right;} .button-action-s.no-me-gusta .icon-pulgarabajo{float:left;margin:2px 11px;margin-right:2px;} ";
	$('head').append('');
	renderButtons();
});

//Fabi
if(window.location.pathname ==='/mi'){
	// /mi
	$('#Feed-list').onResize().on('resize',function(event){
		renderButtons();
	});
}else{
	//shouts
	$('.shouts-list').onResize().on('resize',function(event){
		renderButtons();
	});
}<|endoftext|>


<commit_before>/* global moment */
import Ember from 'ember';
import computed from 'ember-computed-decorators';

const NOVEMBER_2016_RETIREMENT = '2016-11-28T12:00:00-08:00';
const JANUARY_2017_RETIREMENT = '2017-01-20T12:00:00-08:00';
const Q2_2017_TRUSTY_RELEASE = '2017-06-21T12:00:00-08:00';

export default Ember.Component.extend({
  queue: Ember.computed.alias('job.queue'),
  jobConfig: Ember.computed.alias('job.config'),

  conjugatedRun: Ember.computed('job.isFinished', function () {
    if (this.get('job.isFinished')) {
      return 'ran';
    } else {
      return 'is running';
    }
  }),

  isLegacyInfrastructure: Ember.computed.equal('queue', 'builds.linux'),

  isTrustySudoFalse: Ember.computed.equal('queue', 'builds.ec2'),

  @computed('job.startedAt', 'queue', 'job.config')
  isTrustySudoRequired(startedAt, queue, config) {
    if (queue === 'builds.gce' && config.dist === 'trusty' && config.group === 'stable') {
      const jobRanAfterReleaseDate = Date.parse(startedAt) > Q2_2017_TRUSTY_RELEASE;
      if (jobRanAfterReleaseDate) {
        return true;
      }
    }
  },

  isMacStadium6: Ember.computed.equal('queue', 'builds.macstadium6'),

  @computed('queue', 'job.config')
  isPreciseEOL(queue, config) {
    if (queue === 'builds.gce' && config.dist === 'precise') {
      if (config.language !== 'android') {
        return true;
      }
    }
  },

  macOSImage: Ember.computed.alias('jobConfig.osx_image'),

  deprecatedXcodeImages:
    ['beta-xcode6.1', 'beta-xcode6.2', 'beta-xcode6.3', 'xcode7', 'xcode7.1', 'xcode7.2'],

  imageToRetirementDate: {
    'beta-xcode6.1': JANUARY_2017_RETIREMENT,
    'beta-xcode6.2': NOVEMBER_2016_RETIREMENT,
    'beta-xcode6.3': NOVEMBER_2016_RETIREMENT,
    'xcode7': NOVEMBER_2016_RETIREMENT,
    'xcode7.1': NOVEMBER_2016_RETIREMENT,
    'xcode7.2': NOVEMBER_2016_RETIREMENT
  },

  imageToNewImage: {
    'beta-xcode6.1': 'xcode6.4',
    'beta-xcode6.2': 'xcode6.4',
    'beta-xcode6.3': 'xcode6.4',
    'xcode7': 'xcode7.3',
    'xcode7.1': 'xcode7.3',
    'xcode7.2': 'xcode7.3'
  },

  newImageStrings: {
    'xcode7.3': 'Xcode 7.3.1',
    'xcode6.4': 'Xcode 6.4'
  },

  @computed('isMacStadium6', 'macOSImage')
  isDeprecatedOrRetiredMacImage(isMacStadium6, macOSImage) {
    return isMacStadium6 && this.get('deprecatedXcodeImages').includes(macOSImage);
  },

  // eslint-disable-next-line
  @computed('job.startedAt', 'macOSImage', 'job.isFinished', 'conjugatedRun', 'isDeprecatedOrRetiredMacImage')
  deprecatedOrRetiredMacImageMessage(startedAt, image, isFinished, conjugatedRun) {
    const retirementDate = Date.parse(this.get('imageToRetirementDate')[image]);

    const newImage = this.get('imageToNewImage')[image];
    const newImageString = this.get('newImageStrings')[newImage];
    const newImageAnchor = newImageString.replace(' ', '-');
    const newImageURL = `https://docs.travis-ci.com/user/osx-ci-environment/#${newImageAnchor}`;

    const jobRanBeforeRetirementDate = Date.parse(startedAt) < retirementDate;
    const retirementDateIsInTheFuture = retirementDate > new Date();

    const formattedRetirementDate = moment(retirementDate).format('MMMM D, YYYY');

    const retirementLink =
      `${retirementDateIsInTheFuture ? 'will be retired' : 'was retired'}
      on ${formattedRetirementDate}`;

    let retirementSentence, routingSentence;

    if (retirementDateIsInTheFuture) {
      retirementSentence = `This job ${conjugatedRun} on an OS X image that ${retirementLink}.`;
    } else {
      retirementSentence = `
        This job ${isFinished ? 'was configured to run on' : 'is configured to run on'}
        an OS X image that ${retirementLink}.`;
    }

    if (retirementDateIsInTheFuture) {
      routingSentence =
        `After that, it will route to our ${newImageString} infrastructure.`;
    } else if (jobRanBeforeRetirementDate) {
      routingSentence = `New jobs will route to our ${newImageString} infrastructure.`;
    } else {
      routingSentence = `It was routed to our ${newImageString} infrastructure.`;
    }

    return `${retirementSentence} ${routingSentence}`;
  }
});
<commit_msg>Update Trusty update release date (#1144)<commit_after>/* global moment */
import Ember from 'ember';
import computed from 'ember-computed-decorators';

const NOVEMBER_2016_RETIREMENT = '2016-11-28T12:00:00-08:00';
const JANUARY_2017_RETIREMENT = '2017-01-20T12:00:00-08:00';
const Q2_2017_TRUSTY_RELEASE = '2017-06-21T13:00:00-04:00';

export default Ember.Component.extend({
  queue: Ember.computed.alias('job.queue'),
  jobConfig: Ember.computed.alias('job.config'),

  conjugatedRun: Ember.computed('job.isFinished', function () {
    if (this.get('job.isFinished')) {
      return 'ran';
    } else {
      return 'is running';
    }
  }),

  isLegacyInfrastructure: Ember.computed.equal('queue', 'builds.linux'),

  isTrustySudoFalse: Ember.computed.equal('queue', 'builds.ec2'),

  @computed('job.startedAt', 'queue', 'job.config')
  isTrustySudoRequired(startedAt, queue, config) {
    if (queue === 'builds.gce' && config.dist === 'trusty' && config.group === 'stable') {
      const jobRanAfterReleaseDate = Date.parse(startedAt) > Q2_2017_TRUSTY_RELEASE;
      if (jobRanAfterReleaseDate) {
        return true;
      }
    }
  },

  isMacStadium6: Ember.computed.equal('queue', 'builds.macstadium6'),

  @computed('queue', 'job.config')
  isPreciseEOL(queue, config) {
    if (queue === 'builds.gce' && config.dist === 'precise') {
      if (config.language !== 'android') {
        return true;
      }
    }
  },

  macOSImage: Ember.computed.alias('jobConfig.osx_image'),

  deprecatedXcodeImages:
    ['beta-xcode6.1', 'beta-xcode6.2', 'beta-xcode6.3', 'xcode7', 'xcode7.1', 'xcode7.2'],

  imageToRetirementDate: {
    'beta-xcode6.1': JANUARY_2017_RETIREMENT,
    'beta-xcode6.2': NOVEMBER_2016_RETIREMENT,
    'beta-xcode6.3': NOVEMBER_2016_RETIREMENT,
    'xcode7': NOVEMBER_2016_RETIREMENT,
    'xcode7.1': NOVEMBER_2016_RETIREMENT,
    'xcode7.2': NOVEMBER_2016_RETIREMENT
  },

  imageToNewImage: {
    'beta-xcode6.1': 'xcode6.4',
    'beta-xcode6.2': 'xcode6.4',
    'beta-xcode6.3': 'xcode6.4',
    'xcode7': 'xcode7.3',
    'xcode7.1': 'xcode7.3',
    'xcode7.2': 'xcode7.3'
  },

  newImageStrings: {
    'xcode7.3': 'Xcode 7.3.1',
    'xcode6.4': 'Xcode 6.4'
  },

  @computed('isMacStadium6', 'macOSImage')
  isDeprecatedOrRetiredMacImage(isMacStadium6, macOSImage) {
    return isMacStadium6 && this.get('deprecatedXcodeImages').includes(macOSImage);
  },

  // eslint-disable-next-line
  @computed('job.startedAt', 'macOSImage', 'job.isFinished', 'conjugatedRun', 'isDeprecatedOrRetiredMacImage')
  deprecatedOrRetiredMacImageMessage(startedAt, image, isFinished, conjugatedRun) {
    const retirementDate = Date.parse(this.get('imageToRetirementDate')[image]);

    const newImage = this.get('imageToNewImage')[image];
    const newImageString = this.get('newImageStrings')[newImage];
    const newImageAnchor = newImageString.replace(' ', '-');
    const newImageURL = `https://docs.travis-ci.com/user/osx-ci-environment/#${newImageAnchor}`;

    const jobRanBeforeRetirementDate = Date.parse(startedAt) < retirementDate;
    const retirementDateIsInTheFuture = retirementDate > new Date();

    const formattedRetirementDate = moment(retirementDate).format('MMMM D, YYYY');

    const retirementLink =
      `${retirementDateIsInTheFuture ? 'will be retired' : 'was retired'}
      on ${formattedRetirementDate}`;

    let retirementSentence, routingSentence;

    if (retirementDateIsInTheFuture) {
      retirementSentence = `This job ${conjugatedRun} on an OS X image that ${retirementLink}.`;
    } else {
      retirementSentence = `
        This job ${isFinished ? 'was configured to run on' : 'is configured to run on'}
        an OS X image that ${retirementLink}.`;
    }

    if (retirementDateIsInTheFuture) {
      routingSentence =
        `After that, it will route to our ${newImageString} infrastructure.`;
    } else if (jobRanBeforeRetirementDate) {
      routingSentence = `New jobs will route to our ${newImageString} infrastructure.`;
    } else {
      routingSentence = `It was routed to our ${newImageString} infrastructure.`;
    }

    return `${retirementSentence} ${routingSentence}`;
  }
});
<|endoftext|>


<commit_before>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */
/**
 *  TableFormulaDialog.js
 *
 *  Created by Julia Radzhabova on 1/21/19
 *  Copyright (c) 2019 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'common/main/lib/component/InputField',
    'common/main/lib/component/Window'
], function () { 'use strict';

    DE.Views.TableFormulaDialog = Common.UI.Window.extend(_.extend({
        options: {
            width: 300,
            style: 'min-width: 230px;',
            cls: 'modal-dlg'
        },

        initialize : function(options) {
            _.extend(this.options, {
                title: this.textTitle
            }, options || {});

            this.template = [
                '
',
                    '
',
                        '' + this.textFormula + '',
                    '
',
                    '

',
                    '
',
                        '' + this.textFormat + '',
                    '
',
                    '

',
                    '
',
                        '

',
                        '

',
                    '
',
                    '
',
                '
',
                    '<button class="btn normal dlg-btn primary" result="ok" style="margin-right: 10px;">' + this.okButtonText + '</button>',
                    '<button class="btn normal dlg-btn" result="cancel">' + this.cancelButtonText + '</button>',
                '
'
            ].join('');

            this.options.tpl = _.template(this.template)(this.options);
            this.bookmarks = this.options.bookmarks;
            this.api = this.options.api;

            Common.UI.Window.prototype.initialize.call(this, this.options);
        },

        render: function() {
            Common.UI.Window.prototype.render.call(this);

            var me = this,
                $window = this.getChild();

            this.inputFormula = new Common.UI.InputField({
                el          : $('#id-dlg-formula-formula'),
                allowBlank  : true,
                validateOnChange: true,
                style       : 'width: 100%;'
            }).on('changing', _.bind(this.checkFormulaInput, this));

            this.cmbFormat = new Common.UI.ComboBox({
                el          : $('#id-dlg-formula-format'),
                cls         : 'input-group-nr',
                menuStyle   : 'min-width: 100%; max-height: 200px;'
            });

            this.cmbFunction = new Common.UI.ComboBox({
                el          : $('#id-dlg-formula-function'),
                cls         : 'input-group-nr',
                menuStyle   : 'min-width: 100%; max-height: 150px;',
                editable    : false,
                scrollAlwaysVisible: true,
                data: [
                    {displayValue: 'ABS', value: 1},
                    {displayValue: 'AND', value: 1},
                    {displayValue: 'AVERAGE', value: 1},
                    {displayValue: 'COUNT', value: 1},
                    {displayValue: 'DEFINED', value: 1},
                    {displayValue: 'FALSE', value: 0},
                    {displayValue: 'INT', value: 1},
                    {displayValue: 'MAX', value: 1},
                    {displayValue: 'MIN', value: 1},
                    {displayValue: 'MOD', value: 1},
                    {displayValue: 'NOT', value: 1},
                    {displayValue: 'OR', value: 1},
                    {displayValue: 'PRODUCT', value: 1},
                    {displayValue: 'ROUND', value: 1},
                    {displayValue: 'SIGN', value: 1},
                    {displayValue: 'SUM', value: 1},
                    {displayValue: 'TRUE', value: 0}
                ]
            });
            this.cmbFunction.on('selected', _.bind(function(combo, record) {
                combo.setValue(this.textInsertFunction);
                var _input = me.inputFormula._input,
                    end = _input[0].selectionEnd;
                _input.val(_input.val().substring(0, end) + record.displayValue + (record.value ? '()' : '') + _input.val().substring(end));
                _input.focus();
                _input[0].selectionStart = _input[0].selectionEnd = end + record.displayValue.length + record.value;
                this.btnOk.setDisabled(false);
            }, this));
            this.cmbFunction.setValue(this.textInsertFunction);

            this.cmbBookmark = new Common.UI.ComboBox({
                el          : $('#id-dlg-formula-bookmark'),
                cls         : 'input-group-nr',
                menuStyle   : 'min-width: 100%; max-heigh: 150px;',
                editable    : false
            });
            this.cmbBookmark.on('selected', _.bind(function(combo, record) {
                combo.setValue(this.textBookmark);
                var _input = me.inputFormula._input,
                    end = _input[0].selectionEnd;
                _input.val(_input.val().substring(0, end) + record.displayValue + _input.val().substring(end));
                _input.focus();
                _input[0].selectionStart = _input[0].selectionEnd = end + record.displayValue.length;
                this.btnOk.setDisabled(false);
            }, this));
            this.cmbBookmark.setValue(this.textBookmark);

            me.btnOk = new Common.UI.Button({
                el: $window.find('.primary')
            });

            $window.find('.dlg-btn').on('click', _.bind(this.onBtnClick, this));
            this.afterRender();
        },

        onSelectItem: function(picker, item, record, e){
            this.btnOk.setDisabled(record.get('level')==0 && record.get('index')>0);
        },

        show: function() {
            Common.UI.Window.prototype.show.apply(this, arguments);

            var me = this;
            _.delay(function(){
                me.inputFormula.cmpEl.find('input').focus();
            },500);
        },

        afterRender: function() {
            this.refreshBookmarks();
            this._setDefaults();
        },

        _setDefaults: function () {
            var arr = [];
            _.each(this.api.asc_GetTableFormulaFormats(), function(item) {
                arr.push({value: item, displayValue: item});
            });
            this.cmbFormat.setData(arr);
            var formula = this.api.asc_GetTableFormula(),
                idx = formula.lastIndexOf('/\#');
            this.inputFormula.setValue(formula.substring(0, (idx>-1) ? idx : formula.length));
            if (idx>-1)
                this.cmbFormat.setValue(formula.substring(idx+2, formula.length));
            this.checkFormulaInput(this.inputFormula, this.inputFormula.getValue());
        },

        refreshBookmarks: function() {
            var arr = [];
            if (this.bookmarks) {
                var count = this.bookmarks.asc_GetCount();
                for (var i=0; i<count; i++) {
                    var name = this.bookmarks.asc_GetName(i);
                    if (!this.bookmarks.asc_IsInternalUseBookmark(name)) {
                        arr.push({value: i, displayValue: name});
                    }
                }
                this.cmbBookmark.setData(arr);
                this.cmbBookmark.setValue(this.textBookmark);
            }
            this.cmbBookmark.setDisabled(arr.length<1);
        },

        checkFormulaInput: function(cmp, newValue) {
            var value = newValue.trim();
            this.btnOk.setDisabled(value=='' || value == '=');
        },

        getSettings: function () {
            return (this.inputFormula.getValue() + '/\#' + this.cmbFormat.getValue());
        },

        onBtnClick: function(event) {
            this._handleInput(event.currentTarget.attributes['result'].value);
        },

        onPrimary: function(event) {
            this._handleInput('ok');
            return false;
        },

        _handleInput: function(state) {
            if (this.options.handler) {
                this.options.handler.call(this, state, this.getSettings());
            }

            this.close();
        },

        textFormula: 'Formula',
        textFormat: 'Number Format',
        textBookmark: 'Paste Bookmark',
        textInsertFunction: 'Paste Function',
        cancelButtonText:   'Cancel',
        okButtonText:       'Ok',
        textTitle:          'Formula Settings'
    }, DE.Views.TableFormulaDialog || {}))
});<commit_msg>[DE] Fix formula string<commit_after>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */
/**
 *  TableFormulaDialog.js
 *
 *  Created by Julia Radzhabova on 1/21/19
 *  Copyright (c) 2019 Ascensio System SIA. All rights reserved.
 *
 */

define([
    'common/main/lib/component/InputField',
    'common/main/lib/component/Window'
], function () { 'use strict';

    DE.Views.TableFormulaDialog = Common.UI.Window.extend(_.extend({
        options: {
            width: 300,
            style: 'min-width: 230px;',
            cls: 'modal-dlg'
        },

        initialize : function(options) {
            _.extend(this.options, {
                title: this.textTitle
            }, options || {});

            this.template = [
                '
',
                    '
',
                        '' + this.textFormula + '',
                    '
',
                    '

',
                    '
',
                        '' + this.textFormat + '',
                    '
',
                    '

',
                    '
',
                        '

',
                        '

',
                    '
',
                    '
',
                '
',
                    '<button class="btn normal dlg-btn primary" result="ok" style="margin-right: 10px;">' + this.okButtonText + '</button>',
                    '<button class="btn normal dlg-btn" result="cancel">' + this.cancelButtonText + '</button>',
                '
'
            ].join('');

            this.options.tpl = _.template(this.template)(this.options);
            this.bookmarks = this.options.bookmarks;
            this.api = this.options.api;

            Common.UI.Window.prototype.initialize.call(this, this.options);
        },

        render: function() {
            Common.UI.Window.prototype.render.call(this);

            var me = this,
                $window = this.getChild();

            this.inputFormula = new Common.UI.InputField({
                el          : $('#id-dlg-formula-formula'),
                allowBlank  : true,
                validateOnChange: true,
                style       : 'width: 100%;'
            }).on('changing', _.bind(this.checkFormulaInput, this));

            this.cmbFormat = new Common.UI.ComboBox({
                el          : $('#id-dlg-formula-format'),
                cls         : 'input-group-nr',
                menuStyle   : 'min-width: 100%; max-height: 200px;'
            });

            this.cmbFunction = new Common.UI.ComboBox({
                el          : $('#id-dlg-formula-function'),
                cls         : 'input-group-nr',
                menuStyle   : 'min-width: 100%; max-height: 150px;',
                editable    : false,
                scrollAlwaysVisible: true,
                data: [
                    {displayValue: 'ABS', value: 1},
                    {displayValue: 'AND', value: 1},
                    {displayValue: 'AVERAGE', value: 1},
                    {displayValue: 'COUNT', value: 1},
                    {displayValue: 'DEFINED', value: 1},
                    {displayValue: 'FALSE', value: 0},
                    {displayValue: 'INT', value: 1},
                    {displayValue: 'MAX', value: 1},
                    {displayValue: 'MIN', value: 1},
                    {displayValue: 'MOD', value: 1},
                    {displayValue: 'NOT', value: 1},
                    {displayValue: 'OR', value: 1},
                    {displayValue: 'PRODUCT', value: 1},
                    {displayValue: 'ROUND', value: 1},
                    {displayValue: 'SIGN', value: 1},
                    {displayValue: 'SUM', value: 1},
                    {displayValue: 'TRUE', value: 0}
                ]
            });
            this.cmbFunction.on('selected', _.bind(function(combo, record) {
                combo.setValue(this.textInsertFunction);
                var _input = me.inputFormula._input,
                    end = _input[0].selectionEnd;
                _input.val(_input.val().substring(0, end) + record.displayValue + (record.value ? '()' : '') + _input.val().substring(end));
                _input.focus();
                _input[0].selectionStart = _input[0].selectionEnd = end + record.displayValue.length + record.value;
                this.btnOk.setDisabled(false);
            }, this));
            this.cmbFunction.setValue(this.textInsertFunction);

            this.cmbBookmark = new Common.UI.ComboBox({
                el          : $('#id-dlg-formula-bookmark'),
                cls         : 'input-group-nr',
                menuStyle   : 'min-width: 100%; max-heigh: 150px;',
                editable    : false
            });
            this.cmbBookmark.on('selected', _.bind(function(combo, record) {
                combo.setValue(this.textBookmark);
                var _input = me.inputFormula._input,
                    end = _input[0].selectionEnd;
                _input.val(_input.val().substring(0, end) + record.displayValue + _input.val().substring(end));
                _input.focus();
                _input[0].selectionStart = _input[0].selectionEnd = end + record.displayValue.length;
                this.btnOk.setDisabled(false);
            }, this));
            this.cmbBookmark.setValue(this.textBookmark);

            me.btnOk = new Common.UI.Button({
                el: $window.find('.primary')
            });

            $window.find('.dlg-btn').on('click', _.bind(this.onBtnClick, this));
            this.afterRender();
        },

        onSelectItem: function(picker, item, record, e){
            this.btnOk.setDisabled(record.get('level')==0 && record.get('index')>0);
        },

        show: function() {
            Common.UI.Window.prototype.show.apply(this, arguments);

            var me = this;
            _.delay(function(){
                me.inputFormula.cmpEl.find('input').focus();
            },500);
        },

        afterRender: function() {
            this.refreshBookmarks();
            this._setDefaults();
        },

        _setDefaults: function () {
            var arr = [];
            _.each(this.api.asc_GetTableFormulaFormats(), function(item) {
                arr.push({value: item, displayValue: item});
            });
            this.cmbFormat.setData(arr);
            var formula = this.api.asc_GetTableFormula(),
                idx = formula.lastIndexOf('\\#');
            this.inputFormula.setValue(formula.substring(0, (idx>-1) ? idx : formula.length));
            if (idx>-1)
                this.cmbFormat.setValue(formula.substring(idx+2, formula.length));
            this.checkFormulaInput(this.inputFormula, this.inputFormula.getValue());
        },

        refreshBookmarks: function() {
            var arr = [];
            if (this.bookmarks) {
                var count = this.bookmarks.asc_GetCount();
                for (var i=0; i<count; i++) {
                    var name = this.bookmarks.asc_GetName(i);
                    if (!this.bookmarks.asc_IsInternalUseBookmark(name)) {
                        arr.push({value: i, displayValue: name});
                    }
                }
                this.cmbBookmark.setData(arr);
                this.cmbBookmark.setValue(this.textBookmark);
            }
            this.cmbBookmark.setDisabled(arr.length<1);
        },

        checkFormulaInput: function(cmp, newValue) {
            var value = newValue.trim();
            this.btnOk.setDisabled(value=='' || value == '=');
        },

        getSettings: function () {
            return (this.inputFormula.getValue() + '\\#' + this.cmbFormat.getValue());
        },

        onBtnClick: function(event) {
            this._handleInput(event.currentTarget.attributes['result'].value);
        },

        onPrimary: function(event) {
            this._handleInput('ok');
            return false;
        },

        _handleInput: function(state) {
            if (this.options.handler) {
                this.options.handler.call(this, state, this.getSettings());
            }

            this.close();
        },

        textFormula: 'Formula',
        textFormat: 'Number Format',
        textBookmark: 'Paste Bookmark',
        textInsertFunction: 'Paste Function',
        cancelButtonText:   'Cancel',
        okButtonText:       'Ok',
        textTitle:          'Formula Settings'
    }, DE.Views.TableFormulaDialog || {}))
});<|endoftext|>


<commit_before>import React, { Component } from "react";
import gql from "graphql-tag";
import { graphql, withApollo } from "react-apollo";
import { Container, Row, Col, Button, Input } from "reactstrap";
import { TypingField } from "../../generic/core";

const SYSTEMS_SUB = gql`
  subscription DamagedSystemsUpdate($simulatorId: ID) {
    systemsUpdate(simulatorId: $simulatorId, extra: true) {
      id
      name
      damage {
        damaged
        report
        requested
        reactivationCode
        neededReactivationCode
        currentStep
      }
      simulatorId
      type
    }
  }
`;

const extra = [
  "Co2 Scrubbers",
  "Fire",
  "Life Support",
  "Power Adjustment",
  "Transporter Buffer",
  "Turbolift Malfunction",
  "Antimatter Containment",
  "Gravity Systems",
  "Hull Breach",
  "Temperature",
  "Holodeck",
  "Brig Force Field",
  "Oxygen Generators",
  "Warp Field Realignment",
  "Computer Power",
  "Particle Detector",
  "Deuterium Fuel",
  "Water Pipes",
  "Food Replicators",
  "Zoology Pens Force Fields"
];

class DamageReportCore extends Component {
  constructor(props) {
    super(props);
    this.systemSub = null;
    this.state = {
      deck: null,
      room: null,
      selectedSystem: null,
      selectedReport: ""
    };
  }
  componentWillReceiveProps(nextProps) {
    if (!this.systemSub && !nextProps.data.loading) {
      this.systemSub = nextProps.data.subscribeToMore({
        document: SYSTEMS_SUB,
        variables: {
          simulatorId: nextProps.simulator.id
        },
        updateQuery: (previousResult, { subscriptionData }) => {
          return Object.assign({}, previousResult, {
            systems: subscriptionData.data.systemsUpdate
          });
        }
      });
    }
  }
  componentWillUnmount() {
    this.systemSub && this.systemSub();
  }
  selectSystem(id) {
    const systems = this.props.data.systems;
    const selectedSystem = systems.find(s => s.id === id);
    this.setState({
      selectedSystem: id,
      selectedReport: selectedSystem.damage.report || ""
    });
  }
  systemStyle(sys) {
    const obj = {
      listStyle: "none",
      cursor: "pointer"
    };
    if (sys.damage.damaged) {
      obj.color = "red";
    }
    if (!sys.name) {
      obj.color = "purple";
    }
    return obj;
  }
  systemName(sys) {
    if (sys.type === "Shield") {
      return `${sys.name} Shields`;
    }
    if (sys.type === "Engine") {
      return `${sys.name} Engines`;
    }
    return sys.name;
  }
  loadReport(e) {
    const self = this;
    var reader = new FileReader();
    reader.onload = function() {
      const result = this.result;
      self.setState({
        selectedReport: result
      });
    };
    e.target.files[0] && reader.readAsText(e.target.files[0]);
  }
  sendReport = () => {
    const mutation = gql`
      mutation DamageReport($systemId: ID!, $report: String!) {
        damageReport(systemId: $systemId, report: $report)
      }
    `;
    const variables = {
      systemId: this.state.selectedSystem,
      report: this.state.selectedReport
    };
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  reactivationCodeResponse = response => {
    const mutation = gql`
      mutation ReactivationCodeResponse($systemId: ID!, $response: Boolean!) {
        systemReactivationCodeResponse(systemId: $systemId, response: $response)
      }
    `;
    const variables = {
      systemId: this.state.selectedSystem,
      response: response
    };
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  createExtraSystem = sysName => {
    const name = sysName || prompt("What is the name of the system?");
    const systems = this.props.data.systems;
    if (systems.find(s => s.name === name)) {
      this.breakSystem(systems.find(s => s.name === name).id);
      return;
    }
    const mutation = gql`
      mutation CreateExtraSystem($simulatorId: ID!, $params: String!) {
        addSystemToSimulator(
          simulatorId: $simulatorId
          className: "System"
          params: $params
        )
      }
    `;
    const variables = {
      simulatorId: this.props.simulator.id,
      params: JSON.stringify({
        name,
        extra: true,
        damage: { damaged: true }
      })
    };
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  breakSystem = sys => {
    const variables = {
      systemId: sys
    };
    // Break it
    const mutation = gql`
      mutation DamageSystem($systemId: ID!) {
        damageSystem(systemId: $systemId)
      }
    `;
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  repairSystem = () => {
    const { selectedSystem } = this.state;
    const variables = {
      systemId: selectedSystem
    };
    // Fix it
    const mutation = gql`
      mutation RepairSystem($systemId: ID!) {
        repairSystem(systemId: $systemId)
      }
    `;
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  generateReport = steps => {
    const mutation = gql`
      mutation GenerateReport($systemId: ID!, $steps: Int) {
        generateDamageReport(systemId: $systemId, steps: $steps)
      }
    `;
    const variables = { systemId: this.state.selectedSystem, steps };
    this.props.client
      .mutate({
        mutation,
        variables
      })
      .then(res => {
        this.setState({
          selectedReport: res.data.generateDamageReport
        });
      });
  };
  render() {
    if (this.props.data.loading) return null;
    const systems = this.props.data.systems;
    if (!systems) return null;
    const { selectedReport, selectedSystem } = this.state;
    const selectedSystemObj = systems.find(s => s.id === selectedSystem);
    return (
      <Container fluid className="damageReport-core">
        <Row style={{ height: "100%" }}>
          <Col sm={4} className="left-side">

              {systems.filter(s => s.damage.damaged).map(s => (

                  {this.systemName(s)} - {s.damage.currentStep + 1} /{" "}
                  {s.damage.report
                    ? s.damage.report
                        .split(/Step [0-9]+:\n/gi)
                        .filter(st => st && st !== "\n").length
                    : 0}

              ))}

            <Input
              type="select"
              value={"top"}
              size="sm"
              onChange={evt => this.createExtraSystem(evt.target.value)}
            >
              <option disabled value="top">
                Extra Damage
              </option>
              {extra.map(e => (
                <option key={e} value={e}>
                  {e}
                </option>
              ))}
              <option value="">Add System</option>
            </Input>
          </Col>
          <Col sm={8}>
            <TypingField
              value={selectedReport}
              style={{
                textAlign: "left",
                height: "auto",
                fontFamily: "monospace"
              }}
              rows={8}
              controlled={true}
              onChange={e => {
                this.setState({
                  selectedReport: e.target.value
                });
              }}
            />
            {selectedSystemObj && selectedSystemObj.damage.reactivationCode ? (

                <Row style={{ margin: 0 }}>
                  <Col sm={3}>Code:</Col>
                  <Col sm={9}>{selectedSystemObj.damage.reactivationCode}</Col>
                </Row>
                <Row style={{ margin: 0 }}>
                  <Col sm={3}>Actual:</Col>
                  <Col sm={9}>
                    {selectedSystemObj.damage.neededReactivationCode}
                  </Col>
                </Row>
                <Row style={{ margin: 0 }}>
                  <Col sm={8}>
                    <Button
                      onClick={() => {
                        this.reactivationCodeResponse(true);
                      }}
                      size={"sm"}
                      color="success"
                      block
                    >
                      Accept & Fix
                    </Button>
                  </Col>
                  <Col sm={4}>
                    <Button
                      onClick={() => {
                        this.reactivationCodeResponse(false);
                      }}
                      size={"sm"}
                      color="danger"
                      block
                    >
                      Deny
                    </Button>
                  </Col>
                </Row>

            ) : (
              <Row style={{ margin: 0 }}>
                <Col sm={3}>
                  <Button
                    size={"sm"}
                    block
                    color="success"
                    onClick={this.repairSystem}
                  >
                    Repair
                  </Button>
                </Col>
                <Col sm={3}>
                  <Input
                    onChange={this.loadReport.bind(this)}
                    style={{ position: "absolute", opacity: 0 }}
                    type="file"
                    name="file"
                    id="exampleFile"
                  />
                  <Button size={"sm"} block color="info">
                    Load Report
                  </Button>
                </Col>
                <Col sm={3}>
                  <select
                    className="btn btn-warning btn-sm btn-block"
                    onChange={evt =>
                      this.generateReport(parseInt(evt.target.value, 10))
                    }
                    value={"select"}
                  >
                    <option value="select">Generate</option>
                    <option value="5">Short</option>
                    <option value="8">Medium</option>
                    <option value="12">Long</option>
                  </select>
                </Col>
                <Col sm={3}>
                  <Button
                    size={"sm"}
                    block
                    color="primary"
                    onClick={this.sendReport}
                  >
                    Send
                  </Button>
                </Col>
              </Row>
            )}
          </Col>
        </Row>
      </Container>
    );
  }
}
const SYSTEMS_QUERY = gql`
  query DamagedSystems($simulatorId: ID) {
    systems(simulatorId: $simulatorId, extra: true) {
      id
      name
      damage {
        damaged
        report
        requested
        reactivationCode
        neededReactivationCode
        currentStep
      }
      simulatorId
      type
    }
  }
`;

export default graphql(SYSTEMS_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: { simulatorId: ownProps.simulator.id }
  })
})(withApollo(DamageReportCore));
<commit_msg>Update the damage report after it has been sent<commit_after>import React, { Component } from "react";
import gql from "graphql-tag";
import { graphql, withApollo } from "react-apollo";
import { Container, Row, Col, Button, Input } from "reactstrap";
import { TypingField } from "../../generic/core";

const SYSTEMS_SUB = gql`
  subscription DamagedSystemsUpdate($simulatorId: ID) {
    systemsUpdate(simulatorId: $simulatorId, extra: true) {
      id
      name
      damage {
        damaged
        report
        requested
        reactivationCode
        neededReactivationCode
        currentStep
      }
      simulatorId
      type
    }
  }
`;

const extra = [
  "Co2 Scrubbers",
  "Fire",
  "Life Support",
  "Power Adjustment",
  "Transporter Buffer",
  "Turbolift Malfunction",
  "Antimatter Containment",
  "Gravity Systems",
  "Hull Breach",
  "Temperature",
  "Holodeck",
  "Brig Force Field",
  "Oxygen Generators",
  "Warp Field Realignment",
  "Computer Power",
  "Particle Detector",
  "Deuterium Fuel",
  "Water Pipes",
  "Food Replicators",
  "Zoology Pens Force Fields"
];

class DamageReportCore extends Component {
  constructor(props) {
    super(props);
    this.systemSub = null;
    this.state = {
      deck: null,
      room: null,
      selectedSystem: null,
      selectedReport: ""
    };
  }
  componentWillReceiveProps(nextProps) {
    if (!this.systemSub && !nextProps.data.loading) {
      this.systemSub = nextProps.data.subscribeToMore({
        document: SYSTEMS_SUB,
        variables: {
          simulatorId: nextProps.simulator.id
        },
        updateQuery: (previousResult, { subscriptionData }) => {
          return Object.assign({}, previousResult, {
            systems: subscriptionData.data.systemsUpdate
          });
        }
      });
    }
  }
  componentWillUnmount() {
    this.systemSub && this.systemSub();
  }
  selectSystem(id) {
    const systems = this.props.data.systems;
    const selectedSystem = systems.find(s => s.id === id);
    this.setState({
      selectedSystem: id,
      selectedReport: selectedSystem.damage.report || ""
    });
  }
  systemStyle(sys) {
    const obj = {
      listStyle: "none",
      cursor: "pointer"
    };
    if (sys.damage.damaged) {
      obj.color = "red";
    }
    if (!sys.name) {
      obj.color = "purple";
    }
    return obj;
  }
  systemName(sys) {
    if (sys.type === "Shield") {
      return `${sys.name} Shields`;
    }
    if (sys.type === "Engine") {
      return `${sys.name} Engines`;
    }
    return sys.name;
  }
  loadReport(e) {
    const self = this;
    var reader = new FileReader();
    reader.onload = function() {
      const result = this.result;
      self.setState({
        selectedReport: result
      });
    };
    e.target.files[0] && reader.readAsText(e.target.files[0]);
  }
  sendReport = () => {
    const mutation = gql`
      mutation DamageReport($systemId: ID!, $report: String!) {
        damageReport(systemId: $systemId, report: $report)
      }
    `;
    const variables = {
      systemId: this.state.selectedSystem,
      report: this.state.selectedReport
    };
    this.props.client.mutate({
      mutation,
      variables
    });
    setTimeout(() => {
      this.selectSystem(this.state.selectedSystem);
    }, 500);
  };
  reactivationCodeResponse = response => {
    const mutation = gql`
      mutation ReactivationCodeResponse($systemId: ID!, $response: Boolean!) {
        systemReactivationCodeResponse(systemId: $systemId, response: $response)
      }
    `;
    const variables = {
      systemId: this.state.selectedSystem,
      response: response
    };
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  createExtraSystem = sysName => {
    const name = sysName || prompt("What is the name of the system?");
    const systems = this.props.data.systems;
    if (systems.find(s => s.name === name)) {
      this.breakSystem(systems.find(s => s.name === name).id);
      return;
    }
    const mutation = gql`
      mutation CreateExtraSystem($simulatorId: ID!, $params: String!) {
        addSystemToSimulator(
          simulatorId: $simulatorId
          className: "System"
          params: $params
        )
      }
    `;
    const variables = {
      simulatorId: this.props.simulator.id,
      params: JSON.stringify({
        name,
        extra: true,
        damage: { damaged: true }
      })
    };
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  breakSystem = sys => {
    const variables = {
      systemId: sys
    };
    // Break it
    const mutation = gql`
      mutation DamageSystem($systemId: ID!) {
        damageSystem(systemId: $systemId)
      }
    `;
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  repairSystem = () => {
    const { selectedSystem } = this.state;
    const variables = {
      systemId: selectedSystem
    };
    // Fix it
    const mutation = gql`
      mutation RepairSystem($systemId: ID!) {
        repairSystem(systemId: $systemId)
      }
    `;
    this.props.client.mutate({
      mutation,
      variables
    });
  };
  generateReport = steps => {
    const mutation = gql`
      mutation GenerateReport($systemId: ID!, $steps: Int) {
        generateDamageReport(systemId: $systemId, steps: $steps)
      }
    `;
    const variables = { systemId: this.state.selectedSystem, steps };
    this.props.client
      .mutate({
        mutation,
        variables
      })
      .then(res => {
        this.setState({
          selectedReport: res.data.generateDamageReport
        });
      });
  };
  render() {
    if (this.props.data.loading) return null;
    const systems = this.props.data.systems;
    if (!systems) return null;
    const { selectedReport, selectedSystem } = this.state;
    const selectedSystemObj = systems.find(s => s.id === selectedSystem);
    return (
      <Container fluid className="damageReport-core">
        <Row style={{ height: "100%" }}>
          <Col sm={4} className="left-side">

              {systems.filter(s => s.damage.damaged).map(s => (

                  {this.systemName(s)} - {s.damage.currentStep + 1} /{" "}
                  {s.damage.report
                    ? s.damage.report
                        .split(/Step [0-9]+:\n/gi)
                        .filter(st => st && st !== "\n").length
                    : 0}

              ))}

            <Input
              type="select"
              value={"top"}
              size="sm"
              onChange={evt => this.createExtraSystem(evt.target.value)}
            >
              <option disabled value="top">
                Extra Damage
              </option>
              {extra.map(e => (
                <option key={e} value={e}>
                  {e}
                </option>
              ))}
              <option value="">Add System</option>
            </Input>
          </Col>
          <Col sm={8}>
            <TypingField
              value={selectedReport}
              style={{
                textAlign: "left",
                height: "auto",
                fontFamily: "monospace"
              }}
              rows={8}
              controlled={true}
              onChange={e => {
                this.setState({
                  selectedReport: e.target.value
                });
              }}
            />
            {selectedSystemObj && selectedSystemObj.damage.reactivationCode ? (

                <Row style={{ margin: 0 }}>
                  <Col sm={3}>Code:</Col>
                  <Col sm={9}>{selectedSystemObj.damage.reactivationCode}</Col>
                </Row>
                <Row style={{ margin: 0 }}>
                  <Col sm={3}>Actual:</Col>
                  <Col sm={9}>
                    {selectedSystemObj.damage.neededReactivationCode}
                  </Col>
                </Row>
                <Row style={{ margin: 0 }}>
                  <Col sm={8}>
                    <Button
                      onClick={() => {
                        this.reactivationCodeResponse(true);
                      }}
                      size={"sm"}
                      color="success"
                      block
                    >
                      Accept & Fix
                    </Button>
                  </Col>
                  <Col sm={4}>
                    <Button
                      onClick={() => {
                        this.reactivationCodeResponse(false);
                      }}
                      size={"sm"}
                      color="danger"
                      block
                    >
                      Deny
                    </Button>
                  </Col>
                </Row>

            ) : (
              <Row style={{ margin: 0 }}>
                <Col sm={3}>
                  <Button
                    size={"sm"}
                    block
                    color="success"
                    onClick={this.repairSystem}
                  >
                    Repair
                  </Button>
                </Col>
                <Col sm={3}>
                  <Input
                    onChange={this.loadReport.bind(this)}
                    style={{ position: "absolute", opacity: 0 }}
                    type="file"
                    name="file"
                    id="exampleFile"
                  />
                  <Button size={"sm"} block color="info">
                    Load Report
                  </Button>
                </Col>
                <Col sm={3}>
                  <select
                    className="btn btn-warning btn-sm btn-block"
                    onChange={evt =>
                      this.generateReport(parseInt(evt.target.value, 10))
                    }
                    value={"select"}
                  >
                    <option value="select">Generate</option>
                    <option value="5">Short</option>
                    <option value="8">Medium</option>
                    <option value="12">Long</option>
                  </select>
                </Col>
                <Col sm={3}>
                  <Button
                    size={"sm"}
                    block
                    color="primary"
                    onClick={this.sendReport}
                  >
                    Send
                  </Button>
                </Col>
              </Row>
            )}
          </Col>
        </Row>
      </Container>
    );
  }
}
const SYSTEMS_QUERY = gql`
  query DamagedSystems($simulatorId: ID) {
    systems(simulatorId: $simulatorId, extra: true) {
      id
      name
      damage {
        damaged
        report
        requested
        reactivationCode
        neededReactivationCode
        currentStep
      }
      simulatorId
      type
    }
  }
`;

export default graphql(SYSTEMS_QUERY, {
  options: ownProps => ({
    fetchPolicy: "cache-and-network",
    variables: { simulatorId: ownProps.simulator.id }
  })
})(withApollo(DamageReportCore));
<|endoftext|>


<commit_before>'use strict';

sceneLoader[0] = function() {

  // Iniciando a nova cena
  scene[0] = new Game.Scene();
  // Adicionando musica na cena
  scene[0].setMusic("musicaSalaDeAula.mp3");

  // Adicionando uma imagem de fundo
  //var fundoSalaDeAula = new Game.Background("salaDeAula.jpg");
  scene[0].background = new Game.Background("salaDeAula.jpg");
  // Para ajuda no desenvolvimento, colocando um evento de clique no fundo para
  // Mostrar as coordenadas
  var mostraCoordenadasAoClicar = true;
  scene[0].background.click = function(mouse) {
    if (mostraCoordenadasAoClicar) {
      var mousePosition = mouse.data.getLocalPosition(stage);
      console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
    }
  }

  /*var carteiras = new Game.Item("salaDeAula_carteiras.png");
  carteiras.setPosition(960, 857);
  carteiras.setZorder(10);
  carteiras.setInteractive(false);*/
  scene[0].item["carteiras"] = new Game.Item("salaDeAula_carteiras.png");
  scene[0].item["carteiras"].setPosition(960, 857);
  scene[0].item["carteiras"].setZorder(10);
  scene[0].item["carteiras"].setInteractive(false);

  scene[0].item["mesaProfessor"] = new Game.Item("salaDeAula_mesaProfessor.png");
  scene[0].item["mesaProfessor"].setPosition(1400, 550);
  scene[0].item["mesaProfessor"].setZorder(15);
  scene[0].item["mesaProfessor"].setInteractive(false);

  scene[0].addAllItemsToScene();

  // Adiciona uma seta para levar a cena externa
  /*var setaJanela = new Game.Item("seta.png");
  setaJanela.setPosition(1735, 480);
  setaJanela.setScale(0.5);
  setaJanela.addGlowEffect();
  setaJanela.setZorder(1);
  setaJanela.click = function(mouse) {
    changeScene(1); // Muda para a cena exterior
  }

  // Adiciona uma seta para levar ao armario
  var setaArmario = new Game.Item("seta.png");
  setaArmario.setPosition(210, 480);
  setaArmario.setScale(0.5);
  setaArmario.setRotation(180);
  setaArmario.addGlowEffect();
  setaArmario.setZorder(1);
  setaArmario.click = function(mouse) {
    changeScene(2); // Muda para a cena exterior
  }

  // Elementos do ciclo da banana

  // Adicionando o aluno
  var estudanteBananaNormal = new Game.Item("estudanteNormal.png");
  estudanteBananaNormal.setPosition(960, 655);
  estudanteBananaNormal.setZorder(11);

  // Adiconando a banana
  var banana = new Game.Item("banana.png");
  banana.setPosition(980, 730);
  banana.setScale(0.2);
  banana.setZorder(9);
  banana.addGlowEffect();
  banana.click = function(mouse) {
    // Eventos que acontecem imediatamente apos clicar na banana
    disableInteractiveness();
    banana.removeGlow();
    scene[0].background.changeBrightness(100, 600);
    item["carteiras"].changeBrightness(100, 600);
    scene[0].item["mesaProfessor"].changeBrightness(100, 600);
    setaJanela.fadeout(600);
    setaArmario.fadeout(600);

    // Eventos que acontecem apos 0.8 segundos do clique
    setTimeout(function() {
      setaJanela.disable();
      setaArmario.disable();
    }, 800);

    // Eventos que acontecem apos 1.6 segundos do clique
    setTimeout(function() {
      banana.fadeout(600);
      estudanteBananaNormal.fadeout(600);
    }, 1600);

    // Eventos que acontecem apos 2.4 segundos do clique
    setTimeout(function() {
      sistemaDigestivo.enable();
      sistemaDigestivo.fadein(600);
    }, 2400);

    // Eventos que acontecem apos 3.2 segundos do clique
    setTimeout(function() {
      estudanteBananaNormal.disable();
      bananaInfectada.enable();
      bananaInfectada.fadein(600);
    }, 3200);

    // Eventos que acontecem apos 3.6 segundos do clique
    setTimeout(function() {
      coliSeta_12.enable();
      coliSeta_12.fadein(600);
    }, 3600);

    // Eventos que acontecem apos 4 segundos do clique
    setTimeout(function() {
      coliDesencistamento.enable();
      coliDesencistamento.fadein(600);
    }, 4000);

    // Eventos que acontecem apos 4.4 segundos do clique
    setTimeout(function() {
      coliSeta_23.enable();
      coliSeta_23.fadein(600);
    }, 4400);

    // Eventos que acontecem apos 4.8 segundos do clique
    setTimeout(function() {
      coliEncistamento.enable();
      coliEncistamento.fadein(600);
    }, 4800);

    // Eventos que acontecem apos 5.2 segundos do clique
    setTimeout(function() {
      coliSeta_34.enable();
      coliSeta_34.fadein(600);
    }, 5200);

    // Eventos que acontecem apos 5.6 segundos do clique
    setTimeout(function() {
      coliFezes.enable();
      coliFezes.fadein(600);
    }, 5600);

    // Eventos que acontecem apos 6.0 segundos do clique
    setTimeout(function() {
      coliSeta_45.enable();
      coliSeta_45.fadein(600);
    }, 6000);

    // Eventos que acontecem apos 6.4 segundos do clique
    setTimeout(function() {
      coliMosca.enable();
      coliMosca.fadein(600);
    }, 6400);

    // Eventos que acontecem apos 6.8 segundos do clique
    setTimeout(function() {
      coliBotaoFechar.enable();
      coliBotaoFechar.fadein(600);
    }, 6800);

    // Eventos que acontecem apos 7.6 segundos do clique
    setTimeout(function() {
      enableInteractiveness();
    }, 7600);
  }

  // Adiciona a imagem do sistema digestivo - Ciclo Entamoeba Coli
  var sistemaDigestivo = new Game.Item("sistemaDigestivo.png");
  sistemaDigestivo.setPosition(960, 550);
  sistemaDigestivo.setScale(1.3);
  sistemaDigestivo.setZorder(5);
  sistemaDigestivo.setInteractive(false);
  sistemaDigestivo.setAlpha(0);
  sistemaDigestivo.disable();

  // Adiciona a primeira imagem do ciclo Entamoeba Coli
  var bananaInfectada = new Game.Item("temp.jpg");
  bananaInfectada.setPosition(335, 255);
  bananaInfectada.setZorder(5);
  bananaInfectada.setAlpha(0);
  bananaInfectada.disable();

  var coliSeta_12 = new Game.Item("seta.png");
  coliSeta_12.setPosition(337, 514);
  coliSeta_12.setRotation(270);
  coliSeta_12.setScale(0.5);
  coliSeta_12.setZorder(4);
  coliSeta_12.setAlpha(0);
  coliSeta_12.disable();

  // Adiciona a segunda imagem do ciclo Entamoeba Coli
  var coliDesencistamento = new Game.Item("temp.jpg");
  coliDesencistamento.setPosition(335, 770);
  coliDesencistamento.setZorder(5);
  coliDesencistamento.setAlpha(0);
  coliDesencistamento.disable();

  var coliSeta_23 = new Game.Item("seta.png");
  coliSeta_23.setPosition(960, 760);
  coliSeta_23.setRotation(45);
  coliSeta_23.setScale(0.3);
  coliSeta_23.setZorder(4);
  coliSeta_23.setAlpha(0);
  coliSeta_23.disable();

  // Adiciona a terceira imagem do ciclo Entamoeba Coli
  var coliEncistamento = new Game.Item("temp.jpg");
  coliEncistamento.setPosition(1520, 200);
  coliEncistamento.setScale(0.8);
  coliEncistamento.setZorder(5);
  coliEncistamento.setAlpha(0);
  coliEncistamento.disable();

  var coliSeta_34 = new Game.Item("seta.png");
  coliSeta_34.setPosition(1520, 382);
  coliSeta_34.setRotation(270);
  coliSeta_34.setScale(0.4);
  coliSeta_34.setZorder(4);
  coliSeta_34.setAlpha(0);
  coliSeta_34.disable();

  // Adiciona a quarta imagem do ciclo Entamoeba Coli
  var coliFezes = new Game.Item("fezes.png");
  coliFezes.setPosition(1520, 540);
  coliFezes.setScale(0.8);
  coliFezes.setZorder(5);
  coliFezes.setAlpha(0);
  coliFezes.disable();

  var coliSeta_45 = new Game.Item("seta.png");
  coliSeta_45.setPosition(1520, 706);
  coliSeta_45.setRotation(270);
  coliSeta_45.setScale(0.4);
  coliSeta_45.setZorder(4);
  coliSeta_45.setAlpha(0);
  coliSeta_45.disable();

  // Adiciona a quinta imagem do ciclo Entamoeba Coli
  var coliMosca = new Game.Item("temp.jpg");
  coliMosca.setPosition(1520, 880);
  coliMosca.setScale(0.8);
  coliMosca.setZorder(5);
  coliMosca.setAlpha(0);
  coliMosca.disable();

  var coliBotaoFechar = new Game.Item("botaoFechar.png");
  coliBotaoFechar.setPosition(1850, 78);
  coliBotaoFechar.setAlpha(0);
  coliBotaoFechar.disable();*/
}
<commit_msg>cycle working with the new scene 'creator'<commit_after>'use strict';

sceneLoader[0] = function() {

  // Iniciando a nova cena
  scene[0] = new Game.Scene();
  // Adicionando musica na cena
  scene[0].setMusic("musicaSalaDeAula.mp3");

  // Adicionando uma imagem de fundo
  //var fundoSalaDeAula = new Game.Background("salaDeAula.jpg");
  scene[0].background = new Game.Background("salaDeAula.jpg");
  // Para ajuda no desenvolvimento, colocando um evento de clique no fundo para
  // Mostrar as coordenadas
  var mostraCoordenadasAoClicar = true;
  scene[0].background.click = function(mouse) {
    if (mostraCoordenadasAoClicar) {
      var mousePosition = mouse.data.getLocalPosition(stage);
      console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
    }
  }

  /*var carteiras = new Game.Item("salaDeAula_carteiras.png");
  carteiras.setPosition(960, 857);
  carteiras.setZorder(10);
  carteiras.setInteractive(false);*/
  scene[0].item["carteiras"] = new Game.Item("salaDeAula_carteiras.png");
  scene[0].item.carteiras.setPosition(960, 857);
  scene[0].item.carteiras.setZorder(10);
  scene[0].item.carteiras.setInteractive(false);

  scene[0].item["mesaProfessor"] = new Game.Item("salaDeAula_mesaProfessor.png");
  scene[0].item.mesaProfessor.setPosition(1400, 550);
  scene[0].item.mesaProfessor.setZorder(15);
  scene[0].item.mesaProfessor.setInteractive(false);

  // Adiciona uma seta para levar a cena externa
  scene[0].item["setaJanela"] = new Game.Item("seta.png");
  scene[0].item.setaJanela.setPosition(1735, 480);
  scene[0].item.setaJanela.setScale(0.5);
  scene[0].item.setaJanela.addGlowEffect();
  scene[0].item.setaJanela.setZorder(1);
  scene[0].item.setaJanela.click = function(mouse) {
    changeScene(1); // Muda para a cena exterior
  }

  // Adiciona uma seta para levar ao armario
  scene[0].item["setaArmario"] = new Game.Item("seta.png");
  scene[0].item.setaArmario.setPosition(210, 480);
  scene[0].item.setaArmario.setScale(0.5);
  scene[0].item.setaArmario.setRotation(180);
  scene[0].item.setaArmario.addGlowEffect();
  scene[0].item.setaArmario.setZorder(1);
  scene[0].item.setaArmario.click = function(mouse) {
    changeScene(2); // Muda para a cena exterior
  }

  // Elementos do ciclo da banana

  // Adicionando o aluno
  scene[0].item["estudanteBananaNormal"] = new Game.Item("estudanteNormal.png");
  scene[0].item.estudanteBananaNormal.setPosition(960, 655);
  scene[0].item.estudanteBananaNormal.setZorder(11);

  // Adiconando a banana
  scene[0].item["banana"] = new Game.Item("banana.png");
  scene[0].item.banana.setPosition(980, 730);
  scene[0].item.banana.setScale(0.2);
  scene[0].item.banana.setZorder(9);
  scene[0].item.banana.addGlowEffect();
  scene[0].item.banana.click = function(mouse) {
    // Eventos que acontecem imediatamente apos clicar na banana
    disableInteractiveness();
    scene[0].item.banana.removeGlow();
    scene[0].background.changeBrightness(100, 600);
    scene[0].item.carteiras.changeBrightness(100, 600);
    scene[0].item.mesaProfessor.changeBrightness(100, 600);
    scene[0].item.setaJanela.fadeout(600);
    scene[0].item.setaArmario.fadeout(600);

    // Eventos que acontecem apos 0.8 segundos do clique
    setTimeout(function() {
      scene[0].item.setaJanela.disable();
      scene[0].item.setaArmario.disable();
    }, 800);

    // Eventos que acontecem apos 1.6 segundos do clique
    setTimeout(function() {
      scene[0].item.banana.fadeout(600);
      scene[0].item.estudanteBananaNormal.fadeout(600);
    }, 1600);

    // Eventos que acontecem apos 2.4 segundos do clique
    setTimeout(function() {
      scene[0].item.sistemaDigestivo.enable();
      scene[0].item.sistemaDigestivo.fadein(600);
    }, 2400);

    // Eventos que acontecem apos 3.2 segundos do clique
    setTimeout(function() {
      scene[0].item.estudanteBananaNormal.disable();
      scene[0].item.bananaInfectada.enable();
      scene[0].item.bananaInfectada.fadein(600);
    }, 3200);

    // Eventos que acontecem apos 3.6 segundos do clique
    setTimeout(function() {
      scene[0].item.coliSeta_12.enable();
      scene[0].item.coliSeta_12.fadein(600);
    }, 3600);

    // Eventos que acontecem apos 4 segundos do clique
    setTimeout(function() {
      scene[0].item.coliDesencistamento.enable();
      scene[0].item.coliDesencistamento.fadein(600);
    }, 4000);

    // Eventos que acontecem apos 4.4 segundos do clique
    setTimeout(function() {
      scene[0].item.coliSeta_23.enable();
      scene[0].item.coliSeta_23.fadein(600);
    }, 4400);

    // Eventos que acontecem apos 4.8 segundos do clique
    setTimeout(function() {
      scene[0].item.coliEncistamento.enable();
      scene[0].item.coliEncistamento.fadein(600);
    }, 4800);

    // Eventos que acontecem apos 5.2 segundos do clique
    setTimeout(function() {
      scene[0].item.coliSeta_34.enable();
      scene[0].item.coliSeta_34.fadein(600);
    }, 5200);

    // Eventos que acontecem apos 5.6 segundos do clique
    setTimeout(function() {
      scene[0].item.coliFezes.enable();
      scene[0].item.coliFezes.fadein(600);
    }, 5600);

    // Eventos que acontecem apos 6.0 segundos do clique
    setTimeout(function() {
      scene[0].item.coliSeta_45.enable();
      scene[0].item.coliSeta_45.fadein(600);
    }, 6000);

    // Eventos que acontecem apos 6.4 segundos do clique
    setTimeout(function() {
      scene[0].item.coliMosca.enable();
      scene[0].item.coliMosca.fadein(600);
    }, 6400);

    // Eventos que acontecem apos 6.8 segundos do clique
    setTimeout(function() {
      scene[0].item.coliBotaoFechar.enable();
      scene[0].item.coliBotaoFechar.fadein(600);
    }, 6800);

    // Eventos que acontecem apos 7.6 segundos do clique
    setTimeout(function() {
      enableInteractiveness();
    }, 7600);
  }

  // Adiciona a imagem do sistema digestivo - Ciclo Entamoeba Coli
  scene[0].item["sistemaDigestivo"] = new Game.Item("sistemaDigestivo.png");
  scene[0].item.sistemaDigestivo.setPosition(960, 550);
  scene[0].item.sistemaDigestivo.setScale(1.3);
  scene[0].item.sistemaDigestivo.setZorder(5);
  scene[0].item.sistemaDigestivo.setInteractive(false);
  scene[0].item.sistemaDigestivo.setAlpha(0);
  scene[0].item.sistemaDigestivo.disable();

  // Adiciona a primeira imagem do ciclo Entamoeba Coli
  scene[0].item["bananaInfectada"] = new Game.Item("temp.jpg");
  scene[0].item.bananaInfectada.setPosition(335, 255);
  scene[0].item.bananaInfectada.setZorder(5);
  scene[0].item.bananaInfectada.setAlpha(0);
  scene[0].item.bananaInfectada.disable();

  scene[0].item["coliSeta_12"] = new Game.Item("seta.png");
  scene[0].item.coliSeta_12.setPosition(337, 514);
  scene[0].item.coliSeta_12.setRotation(270);
  scene[0].item.coliSeta_12.setScale(0.5);
  scene[0].item.coliSeta_12.setZorder(4);
  scene[0].item.coliSeta_12.setAlpha(0);
  scene[0].item.coliSeta_12.disable();

  // Adiciona a segunda imagem do ciclo Entamoeba Coli
  scene[0].item["coliDesencistamento"] = new Game.Item("temp.jpg");
  scene[0].item.coliDesencistamento.setPosition(335, 770);
  scene[0].item.coliDesencistamento.setZorder(5);
  scene[0].item.coliDesencistamento.setAlpha(0);
  scene[0].item.coliDesencistamento.disable();

  scene[0].item["coliSeta_23"] = new Game.Item("seta.png");
  scene[0].item.coliSeta_23.setPosition(960, 760);
  scene[0].item.coliSeta_23.setRotation(45);
  scene[0].item.coliSeta_23.setScale(0.3);
  scene[0].item.coliSeta_23.setZorder(4);
  scene[0].item.coliSeta_23.setAlpha(0);
  scene[0].item.coliSeta_23.disable();

  // Adiciona a terceira imagem do ciclo Entamoeba Coli
  scene[0].item["coliEncistamento"] = new Game.Item("temp.jpg");
  scene[0].item.coliEncistamento.setPosition(1520, 200);
  scene[0].item.coliEncistamento.setScale(0.8);
  scene[0].item.coliEncistamento.setZorder(5);
  scene[0].item.coliEncistamento.setAlpha(0);
  scene[0].item.coliEncistamento.disable();

  scene[0].item["coliSeta_34"] = new Game.Item("seta.png");
  scene[0].item.coliSeta_34.setPosition(1520, 382);
  scene[0].item.coliSeta_34.setRotation(270);
  scene[0].item.coliSeta_34.setScale(0.4);
  scene[0].item.coliSeta_34.setZorder(4);
  scene[0].item.coliSeta_34.setAlpha(0);
  scene[0].item.coliSeta_34.disable();

  // Adiciona a quarta imagem do ciclo Entamoeba Coli
  scene[0].item["coliFezes"] = new Game.Item("fezes.png");
  scene[0].item.coliFezes.setPosition(1520, 540);
  scene[0].item.coliFezes.setScale(0.8);
  scene[0].item.coliFezes.setZorder(5);
  scene[0].item.coliFezes.setAlpha(0);
  scene[0].item.coliFezes.disable();

  scene[0].item["coliSeta_45"] = new Game.Item("seta.png");
  scene[0].item.coliSeta_45.setPosition(1520, 706);
  scene[0].item.coliSeta_45.setRotation(270);
  scene[0].item.coliSeta_45.setScale(0.4);
  scene[0].item.coliSeta_45.setZorder(4);
  scene[0].item.coliSeta_45.setAlpha(0);
  scene[0].item.coliSeta_45.disable();

  // Adiciona a quinta imagem do ciclo Entamoeba Coli
  scene[0].item["coliMosca"] = new Game.Item("temp.jpg");
  scene[0].item.coliMosca.setPosition(1520, 880);
  scene[0].item.coliMosca.setScale(0.8);
  scene[0].item.coliMosca.setZorder(5);
  scene[0].item.coliMosca.setAlpha(0);
  scene[0].item.coliMosca.disable();

  scene[0].item["coliBotaoFechar"] = new Game.Item("botaoFechar.png");
  scene[0].item.coliBotaoFechar.setPosition(1850, 78);
  scene[0].item.coliBotaoFechar.setAlpha(0);
  scene[0].item.coliBotaoFechar.disable();

  scene[0].addAllItemsToScene();
}
<|endoftext|>


<commit_before>"use strict";

const MongoClient = require("mongodb").MongoClient;
const debug = require("debug")("bot-express:memory");
const assert = require('assert');
Promise = require("bluebird");

class MemoryMongodb {
    constructor(options){
        this.url = options.url;
    }

    get(key){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').findOne({context_id: key).then((response) => {
                    debug(response);
                    return resolve(response);
                }).catch((error) => {
                    return reject(error);
                });
            });
        });
    }

    put(key, value, retention){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                value.context_id = key;
                return db.collection('bot-express').insertOne(value, function(err, r) {
                    try {
                        assert.equal(null, err);
                        assert.equal(1, r.insertedCount);
                        return resolve();
                    } catch(e) {
                        return reject(e);
                    }
                });
            });
        });
    }

    del(key){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').deleteOne({context_id: key}, function(err, r) {
                    try {
                        assert.equal(null, err);
                        assert.equal(1, r.insertedCount);
                        return resolve();
                    } catch(e) {
                        return reject(e);
                    }
                });
            });
        });
    }
}

module.exports = MemoryMongodb;
<commit_msg>improving<commit_after>"use strict";

const MongoClient = require("mongodb").MongoClient;
const debug = require("debug")("bot-express:memory");
const assert = require('assert');
Promise = require("bluebird");

class MemoryMongodb {
    constructor(options){
        this.url = options.url;
    }

    get(key){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').findOne({context_id: key}).then((response) => {
                    debug(response);
                    return resolve(response);
                }).catch((error) => {
                    return reject(error);
                });
            });
        });
    }

    put(key, value, retention){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                value.context_id = key;
                return db.collection('bot-express').insertOne(value).then((response) => {
                    assert.equal(1, response.insertedCount);
                    return resolve();
                }).catch((error) => {
                    return reject(error);
                });
            });
        });
    }

    del(key){
        return new Promise((resolve, reject) => {
            return MongoClient.connect(this.url, function(err, db) {
                assert.equal(null, err);
                debug("Connected successfully to MongoDB server");

                return db.collection('bot-express').deleteOne({context_id: key}, function(err, r) {
                    try {
                        assert.equal(null, err);
                        assert.equal(1, r.insertedCount);
                        return resolve();
                    } catch(e) {
                        return reject(e);
                    }
                });
            });
        });
    }
}

module.exports = MemoryMongodb;
<|endoftext|>