<commit_before>// Sample view

enyo.kind({
	name: "moon.sample.music.TrackOneColumnNarrowSample",
	kind: "moon.Panels",
	pattern: "alwaysviewing",
	classes: "moon-neutral",  // TODO: this should be applied automatically by moon.Panels for alwaysviewing
	components: [
		{
			kind: "moon.Panel",
			title: "Browse Tracks",
			titleAbove: "02",
			titleBelow: "",
			headerComponents: [
				{kind: "moon.IconButton", src: "../assets/icon-album.png"},
				{kind: "moon.IconButton", src: "../assets/icon-list.png"}
			],
			components: [
				{
					name: "trackList",
					kind: "moon.DataList",
					scrollerOptions: { kind:"moon.Scroller", horizontal: "hidden" },
					fit: true,
					components: [
						{
							kind: "moon.Item",
							ontap: "changeName",
							components: [
								{
									kind: "enyo.Table",
									components: [
										{
											components: [
												{
													components: [
														{
															kind: "enyo.Image",
															bindings: [
																{from: ".model.coverUrl", to: ".src"}
															]

														}
													],
													attributes: {rowspan: "2"}
												},
												{
													bindings: [
														{from: ".model.track", to: ".content"}
													]
												},
												{
													bindings: [
														{from: ".model.time", to: ".content"}
													],
													attributes: {rowspan: "2"}
												}
											]
										},
										{
											components: [
												{
													bindings: [
														{from: ".model.artist", to: ".content"}
													] ,

													classes: "moon-superscript"
												}
											]
										}
									]
								}
							]
						}
					]
				}
			]
		}
	],
	bindings: [
		{from: ".controller.track", to: ".$.trackList.controller"}
	]
});

// Sample Model

enyo.ready(function (){
	var sampleModel = new enyo.Model({
		track: new enyo.Collection([
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"}
		])
	});

// Sample Application

	new enyo.Application({
		view: {
			classes: "enyo-unselectable moon",
			style: "background-image: url(../assets/livetv-background.png); background-size: 100% 100%;",
			components: [
				{
					kind: "moon.sample.music.TrackOneColumnNarrowSample",
					controller: ".app.controllers.trackController",
					classes: "enyo-fit"
				}
			]
		},
		controllers: [
			{
				name: "trackController",
				kind: "enyo.ModelController",
				model: sampleModel,
				changeName: function(inSender, inEvent) {
					inSender.parent.controller.set("track", "Good track");
				}
			}
		]
	});
});<commit_msg>Fixing Music TrackOneColumnNarrow Sample<commit_after>// Sample view

enyo.kind({
	name: "moon.sample.music.TrackOneColumnNarrowSample",
	components: [{
		kind: "moon.Panels",
		pattern: "alwaysviewing",
		components: [
			{
				kind: "moon.Panel",
				title: "Browse Tracks",
				titleAbove: "02",
				titleBelow: "",
				headerComponents: [
					{kind: "moon.IconButton", src: "../assets/icon-album.png"},
					{kind: "moon.IconButton", src: "../assets/icon-list.png"}
				],
				components: [
					{
						name: "trackList",
						kind: "moon.DataList",
						scrollerOptions: { kind:"moon.Scroller", horizontal: "hidden" },
						fit: true,
						components: [
							{
								kind: "moon.Item",
								ontap: "changeName",
								components: [
									{
										kind: "enyo.Table",
										components: [
											{
												components: [
													{
														components: [
															{
																kind: "enyo.Image",
																bindings: [
																	{from: ".model.coverUrl", to: ".src"}
																]

															}
														],
														attributes: {rowspan: "2"}
													},
													{
														bindings: [
															{from: ".model.track", to: ".content"}
														]
													},
													{
														bindings: [
															{from: ".model.time", to: ".content"}
														],
														attributes: {rowspan: "2"}
													}
												]
											},
											{
												components: [
													{
														bindings: [
															{from: ".model.artist", to: ".content"}
														] ,

														classes: "moon-superscript"
													}
												]
											}
										]
									}
								]
							}
						]
					}
				]
			}
		]
	}],
	bindings: [
		{from: ".controller.track", to: ".$.trackList.controller"}
	]
});

// Sample Model

enyo.ready(function (){
	var sampleModel = new enyo.Model({
		track: new enyo.Collection([
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"},
			{coverUrl: "../assets/default-music.png", track: "Track name", artist: "Artist name", time: "3:40"}
		])
	});

// Sample Application

	new enyo.Application({
		view: {
			classes: "enyo-unselectable moon",
			style: "background-image: url(../assets/livetv-background.png); background-size: 100% 100%;",
			components: [
				{
					kind: "moon.sample.music.TrackOneColumnNarrowSample",
					controller: ".app.controllers.trackController",
					classes: "enyo-fit"
				}
			]
		},
		controllers: [
			{
				name: "trackController",
				kind: "enyo.ModelController",
				model: sampleModel,
				changeName: function(inSender, inEvent) {
					inSender.parent.controller.set("track", "Good track");
				}
			}
		]
	});
});<|endoftext|>


<commit_before>ZBase.registerView((function() {
  var logfile;

  var init = function(path) {
    var path_prefix = "/a/logs/";
    logfile = path.substr(path_prefix.length);

    load();
  }

  var load = function() {
    $.httpGet("/api/v1/logfiles/get_definition?logfile=" + logfile, function(r) {
      if (r.status == 200) {
        render(JSON.parse(r.response));
      } else {
        $.fatalError();
      }
    });
  };

  var render = function(def) {
    var page = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_logfile_editor_tpl");

    $("h1", page).innerHTML = def.name;

    renderRegexPane($(".editor_pane.regex", page), def.regex);

    renderFields(
        $(".editor_pane.source_fields", page),
        def.source_fields,
        deleteSourceField);

    renderFields(
        $(".editor_pane.row_fields", page),
        def.row_fields,
        deleteRowField);

    $.onClick($(".editor_pane.source_fields .add_field", page), addSourceField);
    $.onClick($(".editor_pane.row_fields .add_field", page), addRowField);

    $.handleLinks(page);
    $.replaceViewport(page);
  };

  var renderRegexPane = function(elem, regex) {
    var textarea = $("textarea", elem);
    textarea.value = regex;

    $.onClick($("button.submit", elem), function() {
      var url = "/api/v1/logfiles/set_regex?logfile=" + logfile;
      var postbody = {regex: textarea.value};

      $.httpPost(url, postbody, function(r) {
        if (r.status == 201) {
          load();
        } else {
          $.fatalError();
        }
      });
    });
  };

  var renderFields = function(elem, fields, onDelete) {
    var tbody = $("tbody", elem);
    var tr_tpl = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_logfile_editor_row_tpl");

    fields.forEach(function(field) {
      var tr = tr_tpl.cloneNode(true);
      $(".name", tr).innerHTML = field.name;
      $(".type", tr).innerHTML = field.type;
      $(".format", tr).innerHTML = field.format;

      $.onClick($(".delete", tr), function() {onDelete(field);});

      tbody.appendChild(tr);
    });
  };

  var addSourceField = function() {
    renderAdd("Add Source Field", function(field) {
      return (
          "/api/v1/logfiles/add_source_field?logfile=" +
          logfile + "&" + $.buildQueryString(field));
    });
  };

  var addRowField = function() {
    renderAdd("Add Row Field", function(field) {
      return (
          "/api/v1/logfiles/add_row_field?logfile=" +
          logfile + "&" + $.buildQueryString(field));
    });
  };

  var deleteSourceField = function(field) {
    renderDelete(field.name, "Delete Source Field", function(def) {
      return (
          "/api/v1/logfiles/remove_source_field?logfile=" +
          logfile + "&name=" + field.name);
    });
  };

  var deleteRowField = function(field) {
    renderDelete(field.name, "Delete Row Field", function() {
     return (
          "/api/v1/logfiles/remove_row_field?logfile=" +
          logfile + "&name=" + field.name);
    });
  };

  var renderAdd = function(header, get_post_url) {
    var modal = $(".zbase_logviewer .logfile_editor z-modal.edit_field");
    var tpl = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_logfile_editor_modal_tpl");

    $(".z-modal-header", tpl).innerHTML = header;

    $.onClick($("button.close", tpl), function() {
      modal.close();
    });

    var name_input = $("input.name", tpl);
    $.onClick($("button.submit", tpl), function() {
      var def = {};
      var error = false;

      //name validation
      def.name = $.escapeHTML(name_input.value);
      if (def.name.length == 0) {
        $(".error_note.name", modal).classList.remove("hidden");
        name_input.classList.add("error");
        name_input.focus();
        error = true;
      } else {
        $(".error_note.name", modal).classList.add("hidden");
        name_input.classList.remove("error");
      }

      var format_input = $("input.format", modal);
      def.format = $.escapeHTML(format_input.value);

      //type format validation
      def.type = $("z-dropdown", modal).getValue();
      if (def.type == "DATETIME" && def.format.length == 0) {
        $(".error_note.date_time_format", modal).classList.remove("hidden");
        format_input.classList.add("error");

        if (!error) {
          format_input.focus();
        }
        error = true;
      } else {
        $(".error_note.date_time_format", modal).classList.add("hidden");
        format_input.classList.remove("error");
      }

      if (!error) {
        $.httpPost(get_post_url(def), "", function(r) {
          if (r.status == 201) {
            load();
          } else {
            $.fatalError(r.statusText);
          }
        });
      }
    });

    $.replaceContent($(".container", modal), tpl);
    modal.show();
    name_input.focus();
  };

  var renderDelete = function(field_name, header, get_post_url) {
    var modal =  $(".zbase_logviewer .logfile_editor z-modal.delete_field");
    var tpl = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_logfile_editor_delete_modal_tpl");

    $(".z-modal-header", tpl).innerHTML = header;
    $(".field_name", tpl).innerHTML = field_name;

    $.onClick($("button.close", tpl), function() {
      modal.close();
    });

    $.onClick($("button.submit", tpl), function() {
      $.httpPost(get_post_url(), "", function(r) {
        if (r.status == 201) {
          load();
        } else {
          $.fatalError(r.statusText);
        }
      });
    });

    $.replaceContent($(".container", modal), tpl);
    modal.show();
  };

  return {
    name: "logviewer_logfile_editor",
    loadView: function(params) { init(params.path); },
    unloadView: function() {},
    handleNavigationChange: init
  };
})());
<commit_msg>logfile editor: url encoding<commit_after>ZBase.registerView((function() {
  var logfile;

  var init = function(path) {
    var path_prefix = "/a/logs/";
    logfile = path.substr(path_prefix.length);

    load();
  }

  var load = function() {
    $.httpGet("/api/v1/logfiles/get_definition?logfile=" + logfile, function(r) {
      if (r.status == 200) {
        render(JSON.parse(r.response));
      } else {
        $.fatalError();
      }
    });
  };

  var render = function(def) {
    var page = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_logfile_editor_tpl");

    $("h1", page).innerHTML = def.name;

    renderRegexPane($(".editor_pane.regex", page), def.regex);

    renderFields(
        $(".editor_pane.source_fields", page),
        def.source_fields,
        deleteSourceField);

    renderFields(
        $(".editor_pane.row_fields", page),
        def.row_fields,
        deleteRowField);

    $.onClick($(".editor_pane.source_fields .add_field", page), addSourceField);
    $.onClick($(".editor_pane.row_fields .add_field", page), addRowField);

    $.handleLinks(page);
    $.replaceViewport(page);
  };

  var renderRegexPane = function(elem, regex) {
    var textarea = $("textarea", elem);
    textarea.value = regex;

    $.onClick($("button.submit", elem), function() {
      var url =
        "/api/v1/logfiles/set_regex?logfile=" + encodeURIComponent(logfile) +
        "&regex=" + encodeURIComponent(textarea.value);

      $.httpPost(url, "", function(r) {
        if (r.status == 201) {
          console.log(r);
          //load();
        } else {
          $.fatalError();
        }
      });
    });
  };

  var renderFields = function(elem, fields, onDelete) {
    var tbody = $("tbody", elem);
    var tr_tpl = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_logfile_editor_row_tpl");

    fields.forEach(function(field) {
      var tr = tr_tpl.cloneNode(true);
      $(".name", tr).innerHTML = field.name;
      $(".type", tr).innerHTML = field.type;
      $(".format", tr).innerHTML = field.format;

      $.onClick($(".delete", tr), function() {onDelete(field);});

      tbody.appendChild(tr);
    });
  };

  var addSourceField = function() {
    renderAdd("Add Source Field", function(field) {
      return (
          "/api/v1/logfiles/add_source_field?logfile=" +
          logfile + "&" + $.buildQueryString(field));
    });
  };

  var addRowField = function() {
    renderAdd("Add Row Field", function(field) {
      return (
          "/api/v1/logfiles/add_row_field?logfile=" +
          logfile + "&" + $.buildQueryString(field));
    });
  };

  var deleteSourceField = function(field) {
    renderDelete(field.name, "Delete Source Field", function(def) {
      return (
          "/api/v1/logfiles/remove_source_field?logfile=" +
          logfile + "&name=" + field.name);
    });
  };

  var deleteRowField = function(field) {
    renderDelete(field.name, "Delete Row Field", function() {
     return (
          "/api/v1/logfiles/remove_row_field?logfile=" +
          logfile + "&name=" + field.name);
    });
  };

  var renderAdd = function(header, get_post_url) {
    var modal = $(".zbase_logviewer .logfile_editor z-modal.edit_field");
    var tpl = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_logfile_editor_modal_tpl");

    $(".z-modal-header", tpl).innerHTML = header;

    $.onClick($("button.close", tpl), function() {
      modal.close();
    });

    var name_input = $("input.name", tpl);
    $.onClick($("button.submit", tpl), function() {
      var def = {};
      var error = false;

      //name validation
      def.name = $.escapeHTML(name_input.value);
      if (def.name.length == 0) {
        $(".error_note.name", modal).classList.remove("hidden");
        name_input.classList.add("error");
        name_input.focus();
        error = true;
      } else {
        $(".error_note.name", modal).classList.add("hidden");
        name_input.classList.remove("error");
      }

      var format_input = $("input.format", modal);
      def.format = $.escapeHTML(format_input.value);

      //type format validation
      def.type = $("z-dropdown", modal).getValue();
      if (def.type == "DATETIME" && def.format.length == 0) {
        $(".error_note.date_time_format", modal).classList.remove("hidden");
        format_input.classList.add("error");

        if (!error) {
          format_input.focus();
        }
        error = true;
      } else {
        $(".error_note.date_time_format", modal).classList.add("hidden");
        format_input.classList.remove("error");
      }

      if (!error) {
        $.httpPost(get_post_url(def), "", function(r) {
          if (r.status == 201) {
            load();
          } else {
            $.fatalError(r.statusText);
          }
        });
      }
    });

    $.replaceContent($(".container", modal), tpl);
    modal.show();
    name_input.focus();
  };

  var renderDelete = function(field_name, header, get_post_url) {
    var modal =  $(".zbase_logviewer .logfile_editor z-modal.delete_field");
    var tpl = $.getTemplate(
        "views/logviewer",
        "zbase_logviewer_logfile_editor_delete_modal_tpl");

    $(".z-modal-header", tpl).innerHTML = header;
    $(".field_name", tpl).innerHTML = field_name;

    $.onClick($("button.close", tpl), function() {
      modal.close();
    });

    $.onClick($("button.submit", tpl), function() {
      $.httpPost(get_post_url(), "", function(r) {
        if (r.status == 201) {
          load();
        } else {
          $.fatalError(r.statusText);
        }
      });
    });

    $.replaceContent($(".container", modal), tpl);
    modal.show();
  };

  return {
    name: "logviewer_logfile_editor",
    loadView: function(params) { init(params.path); },
    unloadView: function() {},
    handleNavigationChange: init
  };
})());
<|endoftext|>


<commit_before>goog.provide('Blockly.Python.audio');

goog.require('Blockly.Python');

function createAudioParser(audioFile) {
  Blockly.Python[audioFile] = function(block) {
    return ['\"'+ audioFile + '\"', Blockly.Python.ORDER_NONE];
  };
}

function loadAudioParser() {
  var request = new XMLHttpRequest();
  request.open("GET", "/audio/list", true);

  request.onload = function(evt) {
    var response = JSON.parse(request.responseText);

    for(var i=0; i < response.length; i++) {
      createAudioParser(response[i]);
    }
  }

  request.send();
}

Blockly.Python['speaker'] = function(block) {
  Blockly.Python.definitions_['import_speaker'] = 'from hackclock.runapp.Libs.GStreamer import Speaker';
  Blockly.Python.definitions_['init_speaker'] = 'speaker = Speaker()';
  return ['speaker', Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python['google_music_radio'] = function(block) {
  Blockly.Python.definitions_['import_speaker'] = 'from hackclock.runapp.Libs.GStreamer import Speaker';
  Blockly.Python.definitions_['import_googlemusic'] = 'from hackclock.runapp.Libs.GoogleMusic import AudioStream';
  Blockly.Python.definitions_['init_speaker'] = 'speaker = Speaker()';
  Blockly.Python.definitions_['init_googlemusic'] = 'audio_stream = AudioStream()';

  return ['audio_stream', Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python['play_list'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  var value_songs = Blockly.Python.valueToCode(block, 'songs', Blockly.Python.ORDER_ATOMIC);
  return ''+value_speaker+'.playList('+value_songs+')\n';
};

Blockly.Python['volume_up'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  return ''+value_speaker+'.volumeUp()\n';
};

Blockly.Python['volume_down'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  return ''+value_speaker+'.volumeDown()\n';
};

Blockly.Python['is_playing'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  return [value_speaker + '.isPlaying()', Blockly.Python.ORDER_NONE];
};

Blockly.Python['audio_stop'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  return value_speaker + ".stop()\n";
};
<commit_msg>Do not pass around the same GMusic list; create new each time<commit_after>goog.provide('Blockly.Python.audio');

goog.require('Blockly.Python');

function createAudioParser(audioFile) {
  Blockly.Python[audioFile] = function(block) {
    return ['\"'+ audioFile + '\"', Blockly.Python.ORDER_NONE];
  };
}

function loadAudioParser() {
  var request = new XMLHttpRequest();
  request.open("GET", "/audio/list", true);

  request.onload = function(evt) {
    var response = JSON.parse(request.responseText);

    for(var i=0; i < response.length; i++) {
      createAudioParser(response[i]);
    }
  }

  request.send();
}

Blockly.Python['speaker'] = function(block) {
  Blockly.Python.definitions_['import_speaker'] = 'from hackclock.runapp.Libs.GStreamer import Speaker';
  Blockly.Python.definitions_['init_speaker'] = 'speaker = Speaker()';
  return ['speaker', Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python['google_music_radio'] = function(block) {
  Blockly.Python.definitions_['import_speaker'] = 'from hackclock.runapp.Libs.GStreamer import Speaker';
  Blockly.Python.definitions_['import_googlemusic'] = 'from hackclock.runapp.Libs.GoogleMusic import AudioStream';
  Blockly.Python.definitions_['init_speaker'] = 'speaker = Speaker()';

  return ['AudioStream()', Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python['play_list'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  var value_songs = Blockly.Python.valueToCode(block, 'songs', Blockly.Python.ORDER_ATOMIC);
  return ''+value_speaker+'.playList('+value_songs+')\n';
};

Blockly.Python['volume_up'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  return ''+value_speaker+'.volumeUp()\n';
};

Blockly.Python['volume_down'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  return ''+value_speaker+'.volumeDown()\n';
};

Blockly.Python['is_playing'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  return [value_speaker + '.isPlaying()', Blockly.Python.ORDER_NONE];
};

Blockly.Python['audio_stop'] = function(block) {
  var value_speaker = Blockly.Python.valueToCode(block, 'speaker', Blockly.Python.ORDER_ATOMIC);
  return value_speaker + ".stop()\n";
};
<|endoftext|>


<commit_before>// import liraries
import React, { Component } from 'react';
import PropTypes from 'prop-types'
import { View, StyleSheet, Animated, Platform } from 'react-native';
import LinearGradient from 'react-native-linear-gradient'

class CustomLinearGradient extends Component {
  render() {
    const { locationStart, colorShimmer, widthShimmer } = this.props;
    return (
      <LinearGradient
        colors={colorShimmer}
        style={{ flex: 1 }}
        start={{
          x: -1,
          y: 0.5,
        }}
        end={{
          x: 2,
          y: 0.5,
        }}
       //  locations={[0, 0.5, 1]}
        locations={[locationStart + widthShimmer, locationStart + 0.5 + widthShimmer / 2, locationStart + 1]}
      />
    );
  }
}
CustomLinearGradient.propTypes = {
  locationStart: PropTypes.any,
  colorShimmer: PropTypes.array,
  widthShimmer: PropTypes.number,
};

Animated.LinearGradient = Animated.createAnimatedComponent(CustomLinearGradient);

// create a component
class ShimmerPlaceHolder extends Component {
  constructor(props) {
    super(props);
    // this.beginShimmerPosition = new Animated.Value(-1);
    this.state = {
      visible: false,
      beginShimmerPosition: new Animated.Value(-1),
    };
  }
  componentDidMount() {
    const { autoRun } = this.props;
    if (autoRun) {
      this.loopAnimated();
    }
  }
  loopAnimated() {
    const shimmerAnimated = this.getAnimated();
    const { visible } = this.props;
    shimmerAnimated.start(() => {
      if (!visible) {
        this.loopAnimated();
      }
    })
  }
  getAnimated = () => {
    // this.state.color.setValue(0);
    this.state.beginShimmerPosition.setValue(-1);
    return Animated.timing(this.state.beginShimmerPosition, {
      toValue: 1,
      duration: this.props.duration,
      // useNativeDriver: true,
      // easing: Easing.linear,
      // delay: -400
    });
  }
  render() {
    const { width, reverse, height, colorShimmer, style, widthShimmer, children, visible, backgroundColorBehindBorder, hasBorder } = this.props;
    let beginPostioner = -0.7;
    let endPosition = 0.7;
    if (reverse) {
      beginPostioner = 0.7;
      endPosition = -0.7;
    }
    const newValue = this.state.beginShimmerPosition.interpolate({
      inputRange: [-1, 1],
      outputRange: [beginPostioner, endPosition],
    });
    return (
        <View style={!visible
        ? [{ height, width }, styles.container, style]
        : []
        }
        >
          {!visible
          ? (
            <View style={{ flex: 1 }}>
              <Animated.LinearGradient
                locationStart={newValue}
                colorShimmer={colorShimmer}
                widthShimmer={widthShimmer}
              />
              {/* Force run children */}
              <View style={{ width: 0, height: 0 }}>
                {this.props.children}
              </View>
              {((style && style.borderRadius) || hasBorder) && Platform.OS === 'android'
              ? <View style={{
                position: 'absolute',
                top: -40,
                bottom: -40,
                right: -40,
                left: -40,
                borderRadius: width / 2 + 40 / 2,
                borderWidth: 40,
                borderColor: backgroundColorBehindBorder,
              }}
              />
               : null }
            </View>
            )
          : children
          }
        </View>
    );
  }
}
ShimmerPlaceHolder.defaultProps = {
  width: 200,
  height: 15,
  widthShimmer: 0.7,
  duration: 1000,
  colorShimmer: ['#ebebeb', '#c5c5c5', '#ebebeb'],
  reverse: false,
  autoRun: false,
  visible: false,
  backgroundColorBehindBorder: 'white',
  hasBorder: false,
};
// define your styles
const styles = StyleSheet.create({
  container: {
    // flex: 1,
    overflow: 'hidden',
  },
});
ShimmerPlaceHolder.propTypes = {
  width: PropTypes.oneOfType([ PropTypes.number, PropTypes.string ]),
  height: PropTypes.oneOfType([ PropTypes.number, PropTypes.string ]),
  widthShimmer: PropTypes.number,
  duration: PropTypes.number,
  colorShimmer: PropTypes.array,
  reverse: PropTypes.bool,
  autoRun: PropTypes.bool,
  visible: PropTypes.bool,
  children: PropTypes.any,
  style: PropTypes.any,
  backgroundColorBehindBorder: PropTypes.string,
  hasBorder: PropTypes.bool,
};
// make this component available to the app
export default ShimmerPlaceHolder;
<commit_msg>Add success transform<commit_after>// import liraries
import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, StyleSheet, Animated, Platform } from "react-native";
import LinearGradient from "react-native-linear-gradient";

// create a component
class ShimmerPlaceHolder extends Component {
  constructor(props) {
    super(props);
    // this.beginShimmerPosition = new Animated.Value(-1);
    this.state = {
      visible: false,
      beginShimmerPosition: new Animated.Value(-1)
    };
  }
  componentDidMount() {
    const { autoRun } = this.props;
    if (autoRun) {
      this.loopAnimated();
    }
  }
  loopAnimated() {
    const shimmerAnimated = this.getAnimated();
    const { visible } = this.props;
    shimmerAnimated.start(() => {
      if (!visible) {
        this.loopAnimated();
      }
    });
  }
  getAnimated = () => {
    // this.state.color.setValue(0);
    this.state.beginShimmerPosition.setValue(-1);
    return Animated.timing(this.state.beginShimmerPosition, {
      toValue: 1,
      duration: this.props.duration,
      useNativeDriver: true,
      // easing: Easing.linear,
      // delay: -400
    });
  };
  render() {
    const {
      width,
      reverse,
      height,
      colorShimmer,
      style,
      widthShimmer,
      children,
      visible,
      backgroundColorBehindBorder,
      hasBorder
    } = this.props;
    let beginPostioner = -0.7;
    let endPosition = 0.7;
    if (reverse) {
      beginPostioner = 0.7;
      endPosition = -0.7;
    }
    const newValue = this.state.beginShimmerPosition.interpolate({
      inputRange: [-1, 1],
      outputRange: [beginPostioner, endPosition]
    });
    const linearTranslate = this.state.beginShimmerPosition.interpolate({
      inputRange: [-1, 1],
      outputRange: [-width, width]
    });
    return (
      <View
        style={!visible ? [{ height, width }, styles.container, style] : []}
      >
        {!visible ? (
          <View style={{ flex: 1, backgroundColor: colorShimmer[0] }}>

            {/* USING TRANSFORM */}
            <Animated.View style={{flex: 1, transform: [{ translateX: linearTranslate }] }}>
             <LinearGradient
                colors={colorShimmer}
                style={{ flex: 1 }}
                start={{
                  x: -1,
                  y: 0.5
                }}
                end={{
                  x: 2,
                  y: 0.5
                }}
                //  locations={[0, 0.5, 1]}
                locations={[
                  0.3, 0.5, 0.7
                ]}
              />
            </Animated.View>

            {/* Force run children */}
            <View style={{ width: 0, height: 0 }}>{this.props.children}</View>
            {/* If style has border */}
            {((style && style.borderRadius) || hasBorder) &&
            Platform.OS === "android" ? (
              <View
                style={{
                  position: "absolute",
                  top: -40,
                  bottom: -40,
                  right: -40,
                  left: -40,
                  borderRadius: width / 2 + 40 / 2,
                  borderWidth: 40,
                  borderColor: backgroundColorBehindBorder
                }}
              />
            ) : null}
          </View>
        ) : (
          children
        )}
      </View>
    );
  }
}
ShimmerPlaceHolder.defaultProps = {
  width: 200,
  height: 15,
  widthShimmer: 0.7,
  duration: 1000,
  colorShimmer: ["#ebebeb", "#c5c5c5", "#ebebeb"],
  reverse: false,
  autoRun: false,
  visible: false,
  backgroundColorBehindBorder: "white",
  hasBorder: false
};
// define your styles
const styles = StyleSheet.create({
  container: {
    // flex: 1,
    overflow: "hidden"
  }
});
ShimmerPlaceHolder.propTypes = {
  width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  widthShimmer: PropTypes.number,
  duration: PropTypes.number,
  colorShimmer: PropTypes.array,
  reverse: PropTypes.bool,
  autoRun: PropTypes.bool,
  visible: PropTypes.bool,
  children: PropTypes.any,
  style: PropTypes.any,
  backgroundColorBehindBorder: PropTypes.string,
  hasBorder: PropTypes.bool
};
// make this component available to the app
export default ShimmerPlaceHolder;
<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2013 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

/*global google */
pimcore.registerNS("pimcore.settings.targeting.rules.item");
pimcore.settings.targeting.rules.item = Class.create({

    initialize: function(parent, data) {
        this.parent = parent;
        this.data = data;
        this.currentIndex = 0;

        this.tabPanel = new Ext.TabPanel({
            activeTab: 0,
            title: this.data.name,
            closable: true,
            deferredRender: false,
            forceLayout: true,
            id: "pimcore_targeting_panel_" + this.data.id,
            buttons: [{
                text: t("save"),
                iconCls: "pimcore_icon_apply",
                handler: this.save.bind(this)
            }],
            items: [this.getSettings(),this.getConditions(), this.getActions()]
        });

        // fill data into conditions
        if(this.data.conditions && this.data.conditions.length > 0) {
            for(var i=0; i<this.data.conditions.length; i++) {
                this.addCondition("item" + ucfirst(this.data.conditions[i].type), this.data.conditions[i]);
            }
        }

        this.parent.panel.add(this.tabPanel);
        this.parent.panel.activate(this.tabPanel);
        this.parent.panel.doLayout();
    },

    getActions: function () {
        this.actionsForm = new Ext.form.FormPanel({
            layout: "pimcoreform",
            bodyStyle: "padding: 10px",
            title: t("actions"),
            autoScroll: true,
            border:false,
            items: [{
                xtype: "fieldset",
                title: t("redirect"),
                itemId: "actions_redirect",
                collapsible: true,
                collapsed: !this.data.actions.redirectEnabled,
                items: [{
                    xtype: "textfield",
                    width: 350,
                    fieldLabel: "URL",
                    name: "redirect.url",
                    value: this.data.actions.redirectUrl,
                    cls: "input_drop_target",
                    listeners: {
                        "render": function (el) {
                            new Ext.dd.DropZone(el.getEl(), {
                                reference: this,
                                ddGroup: "element",
                                getTargetFromEvent: function(e) {
                                    return this.getEl();
                                }.bind(el),

                                onNodeOver : function(target, dd, e, data) {
                                    return Ext.dd.DropZone.prototype.dropAllowed;
                                },

                                onNodeDrop : function (target, dd, e, data) {
                                    if (data.node.attributes.elementType == "document") {
                                        this.setValue(data.node.attributes.path);
                                        return true;
                                    }
                                    return false;
                                }.bind(el)
                            });
                        }
                    }
                }]
            }, {
                xtype: "fieldset",
                title: t("programmatically"),
                itemId: "actions_programmatically",
                collapsible: true,
                collapsed: !this.data.actions.programmaticallyEnabled,
                items: [{
                    xtype: "displayfield",
                    value: t("in_this_case_a_developer_has_to_implement_a_logic_which_handles_this_action")
                }]
            }, {
                xtype: "fieldset",
                title: t("event"),
                itemId: "actions_event",
                collapsible: true,
                collapsed: !this.data.actions.eventEnabled,
                items: [{
                    xtype: "textfield",
                    name: "event.key",
                    width: 200,
                    fieldLabel: t("key"),
                    value: this.data.actions.eventKey
                }, {
                    xtype: "textfield",
                    name: "event.value",
                    width: 100,
                    fieldLabel: t("value"),
                    value: this.data.actions.eventValue
                }]
            }, {
                xtype: "fieldset",
                itemId: "actions_codesnippet",
                title: t("code_snippet"),
                collapsible: true,
                collapsed: !this.data.actions.codesnippetEnabled,
                items: [{
                    xtype: "textarea",
                    width: 500,
                    height: 200,
                    fieldLabel: t("code"),
                    name: "codesnippet.code",
                    value: this.data.actions.codesnippetCode
                },{
                    xtype:'combo',
                    fieldLabel: t('element_css_selector'),
                    name: "codesnippet.selector",
                    disableKeyFilter: true,
                    store: [["body","body"],["head","head"]],
                    triggerAction: "all",
                    mode: "local",
                    width: 250,
                    value: this.data.actions.codesnippetSelector
                },{
                    xtype:'combo',
                    fieldLabel: t('insert_position'),
                    name: "codesnippet.position",
                    store: [["beginning",t("beginning")],["end",t("end")],["replace",t("replace")]],
                    triggerAction: "all",
                    typeAhead: false,
                    editable: false,
                    forceSelection: true,
                    mode: "local",
                    width: 250,
                    value: this.data.actions.codesnippetPosition
                }]
            }, {
                xtype: "fieldset",
                itemId: "actions_persona",
                title: t('associate_target_group') + " (" + t("personas") + ")",
                collapsible: true,
                collapsed: !this.data.actions.personaEnabled,
                items: [{
                    xtype: "combo",
                    name: "persona.id",
                    displayField:'text',
                    valueField: "id",
                    store: pimcore.globalmanager.get("personas"),
                    editable: false,
                    width: 300,
                    triggerAction: 'all',
                    listWidth: 200,
                    mode: "local",
                    value: this.data.actions.personaId,
                    emptyText: t("select_a_persona")
                }]
            }]
        });

        return this.actionsForm;
    },

    getSettings: function () {

        this.settingsForm = new Ext.form.FormPanel({
            layout: "pimcoreform",
            title: t("settings"),
            bodyStyle: "padding:10px;",
            autoScroll: true,
            border:false,
            items: [{
                xtype: "textfield",
                fieldLabel: t("name"),
                name: "name",
                width: 250,
                disabled: true,
                value: this.data.name
            }, {
                name: "description",
                fieldLabel: t("description"),
                xtype: "textarea",
                width: 400,
                height: 100,
                value: this.data.description
            }, {
                name: "scope",
                fieldLabel: t("scope"),
                xtype: "combo",
                width: 200,
                value: this.data["scope"],
                mode: "local",
                triggerAction: "all",
                store: [["user", t("user")],["session", t("session")], ["hit", t("hit")]]
            }, {
                name: "active",
                fieldLabel: t("active"),
                xtype: "checkbox",
                checked: this.data["active"]
            }]
        });

        return this.settingsForm;
    },

    getConditions: function() {
        var addMenu = [];
        var itemTypes = Object.keys(pimcore.settings.targeting.conditions);
        for(var i=0; i<itemTypes.length; i++) {
            if(itemTypes[i].indexOf("item") == 0) {
                addMenu.push({
                    iconCls: "pimcore_icon_add",
                    handler: this.addCondition.bind(this, itemTypes[i]),
                    text: pimcore.settings.targeting.conditions[itemTypes[i]](null, null,true)
                });
            }
        }

        this.conditionsContainer = new Ext.Panel({
            title: t("conditions"),
            autoScroll: true,
            forceLayout: true,
            tbar: [{
                iconCls: "pimcore_icon_add",
                menu: addMenu
            }],
            border: false
        });

        return this.conditionsContainer;
    },

    addCondition: function (type, data) {

        var item = pimcore.settings.targeting.conditions[type](this, data);

        // add logic for brackets
        var tab = this;
        item.on("afterrender", function (el) {
            el.getEl().applyStyles({position: "relative", "min-height": "40px"});
            var leftBracket = el.getEl().insertHtml("beforeEnd",
                '
(
', true);
            var rightBracket = el.getEl().insertHtml("beforeEnd",
                '
)
', true);

            if(data["bracketLeft"]){
                leftBracket.addClass("pimcore_targeting_bracket_active");
            }
            if(data["bracketRight"]){
                rightBracket.addClass("pimcore_targeting_bracket_active");
            }

            // open
            leftBracket.on("click", function (ev, el) {
                var bracket = Ext.get(el);
                bracket.toggleClass("pimcore_targeting_bracket_active");

                tab.recalculateBracketIdent(tab.conditionsContainer.items);
            });

            // close
            rightBracket.on("click", function (ev, el) {
                var bracket = Ext.get(el);
                bracket.toggleClass("pimcore_targeting_bracket_active");

                tab.recalculateBracketIdent(tab.conditionsContainer.items);
            });

            // make ident
            tab.recalculateBracketIdent(tab.conditionsContainer.items);
        });

        this.conditionsContainer.add(item);
        item.doLayout();
        this.conditionsContainer.doLayout();

        this.currentIndex++;

        this.recalculateButtonStatus();
    },

    save: function () {

        var saveData = {};
        saveData["settings"] = this.settingsForm.getForm().getFieldValues();
        saveData["actions"] = this.actionsForm.getForm().getFieldValues();
        saveData["actions"]["redirect.enabled"] = !this.actionsForm.getComponent("actions_redirect").collapsed;
        saveData["actions"]["event.enabled"] = !this.actionsForm.getComponent("actions_event").collapsed;
        saveData["actions"]["codesnippet.enabled"] = !this.actionsForm.getComponent("actions_codesnippet").collapsed;
        saveData["actions"]["persona.enabled"] = !this.actionsForm.getComponent("actions_persona").collapsed;
        saveData["actions"]["programmatically.enabled"] = !this.actionsForm.getComponent("actions_programmatically")
                                                                                .collapsed;

        var conditionsData = [];
        var condition, tb, operator;
        var conditions = this.conditionsContainer.items.getRange();
        for (var i=0; i<conditions.length; i++) {
            condition = conditions[i].getForm().getFieldValues();

            // get the operator (AND, OR, AND_NOT)
            tb = conditions[i].getTopToolbar();
            if (tb.getComponent("toggle_or").pressed) {
                operator = "or";
            } else if (tb.getComponent("toggle_and_not").pressed) {
                operator = "and_not";
            } else {
                operator = "and";
            }
            condition["operator"] = operator;

            // get the brackets
            condition["bracketLeft"] = Ext.get(conditions[i].getEl().query(".pimcore_targeting_bracket_left")[0])
                                                                .hasClass("pimcore_targeting_bracket_active");
            condition["bracketRight"] = Ext.get(conditions[i].getEl().query(".pimcore_targeting_bracket_right")[0])
                                                                .hasClass("pimcore_targeting_bracket_active");

            conditionsData.push(condition);
        }
        saveData["conditions"] = conditionsData;

        Ext.Ajax.request({
            url: "/admin/reports/targeting/rule-save",
            params: {
                id: this.data.id,
                data: Ext.encode(saveData)
            },
            method: "post",
            success: function () {

            }.bind(this)
        });
    },

    recalculateButtonStatus: function () {
        var conditions = this.conditionsContainer.items.getRange();
        var tb;
        for (var i=0; i<conditions.length; i++) {
            tb = conditions[i].getTopToolbar();
            if(i==0) {
                tb.getComponent("toggle_and").hide();
                tb.getComponent("toggle_or").hide();
                tb.getComponent("toggle_and_not").hide();
            } else {
                tb.getComponent("toggle_and").show();
                tb.getComponent("toggle_or").show();
                tb.getComponent("toggle_and_not").show();
            }
        }
    },

    /**
     * make ident for bracket
     * @param list
     */
    recalculateBracketIdent: function(list) {
        var ident = 0, lastIdent = 0, margin = 20;
        var colors = ["transparent","#007bff", "#00ff99", "#e1a6ff", "#ff3c00", "#000000"];

        list.each(function (condition) {

            // only rendered conditions
            if(condition.rendered == false)
                return;

            // html from this condition
            var item = condition.getEl();

            // apply ident margin
            item.applyStyles({
                "margin-left": margin * ident + "px",
                "margin-right": margin * ident + "px"
            });

            // apply colors
            if(ident > 0)
                item.applyStyles({
                    "border-left": "1px solid " + colors[ident],
                    "border-right": "1px solid " + colors[ident],
                    "padding": "0px 1px"
                });
            else
                item.applyStyles({
                    "border-left": "0px",
                    "border-right": "0px"
                });

            // apply specials :-)
            if(ident == 0)
                item.applyStyles({
                    "margin-top": "10px"
                });
            else if(ident == lastIdent)
                item.applyStyles({
                    "margin-top": "0px",
                    "margin-bottom": "0px",
                    "padding": "1px"
                });
            else
                item.applyStyles({
                    "margin-top": "5px"
                });

            // remeber current ident
            lastIdent = ident;

            // check if a bracket is open
            if(item.select('.pimcore_targeting_bracket_left.pimcore_targeting_bracket_active').getCount() == 1)
            {
                ident++;
            }
            // check if a bracket is close
            else if(item.select('.pimcore_targeting_bracket_right.pimcore_targeting_bracket_active').getCount() == 1)
            {
                if(ident > 0)
                    ident--;
            }
        });
    }
});

<commit_msg>js fixes<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2013 pimcore GmbH (http://www.pimcore.org)
 * @license    http://www.pimcore.org/license     New BSD License
 */

/*global google */
pimcore.registerNS("pimcore.settings.targeting.rules.item");
pimcore.settings.targeting.rules.item = Class.create({

    initialize: function(parent, data) {
        this.parent = parent;
        this.data = data;
        this.currentIndex = 0;

        this.tabPanel = new Ext.TabPanel({
            activeTab: 0,
            title: this.data.name,
            closable: true,
            deferredRender: false,
            forceLayout: true,
            id: "pimcore_targeting_panel_" + this.data.id,
            buttons: [{
                text: t("save"),
                iconCls: "pimcore_icon_apply",
                handler: this.save.bind(this)
            }],
            items: [this.getSettings(),this.getConditions(), this.getActions()]
        });

        // fill data into conditions
        if(this.data.conditions && this.data.conditions.length > 0) {
            for(var i=0; i<this.data.conditions.length; i++) {
                this.addCondition("item" + ucfirst(this.data.conditions[i].type), this.data.conditions[i]);
            }
        }

        this.parent.panel.add(this.tabPanel);
        this.parent.panel.activate(this.tabPanel);
        this.parent.panel.doLayout();
    },

    getActions: function () {
        this.actionsForm = new Ext.form.FormPanel({
            layout: "pimcoreform",
            bodyStyle: "padding: 10px",
            title: t("actions"),
            autoScroll: true,
            border:false,
            items: [{
                xtype: "fieldset",
                title: t("redirect"),
                itemId: "actions_redirect",
                collapsible: true,
                collapsed: !this.data.actions.redirectEnabled,
                items: [{
                    xtype: "textfield",
                    width: 350,
                    fieldLabel: "URL",
                    name: "redirect.url",
                    value: this.data.actions.redirectUrl,
                    cls: "input_drop_target",
                    listeners: {
                        "render": function (el) {
                            new Ext.dd.DropZone(el.getEl(), {
                                reference: this,
                                ddGroup: "element",
                                getTargetFromEvent: function(e) {
                                    return this.getEl();
                                }.bind(el),

                                onNodeOver : function(target, dd, e, data) {
                                    return Ext.dd.DropZone.prototype.dropAllowed;
                                },

                                onNodeDrop : function (target, dd, e, data) {
                                    if (data.node.attributes.elementType == "document") {
                                        this.setValue(data.node.attributes.path);
                                        return true;
                                    }
                                    return false;
                                }.bind(el)
                            });
                        }
                    }
                }]
            }, {
                xtype: "fieldset",
                title: t("programmatically"),
                itemId: "actions_programmatically",
                collapsible: true,
                collapsed: !this.data.actions.programmaticallyEnabled,
                items: [{
                    xtype: "displayfield",
                    value: t("in_this_case_a_developer_has_to_implement_a_logic_which_handles_this_action")
                }]
            }, {
                xtype: "fieldset",
                title: t("event"),
                itemId: "actions_event",
                collapsible: true,
                collapsed: !this.data.actions.eventEnabled,
                items: [{
                    xtype: "textfield",
                    name: "event.key",
                    width: 200,
                    fieldLabel: t("key"),
                    value: this.data.actions.eventKey
                }, {
                    xtype: "textfield",
                    name: "event.value",
                    width: 100,
                    fieldLabel: t("value"),
                    value: this.data.actions.eventValue
                }]
            }, {
                xtype: "fieldset",
                itemId: "actions_codesnippet",
                title: t("code_snippet"),
                collapsible: true,
                collapsed: !this.data.actions.codesnippetEnabled,
                items: [{
                    xtype: "textarea",
                    width: 500,
                    height: 200,
                    fieldLabel: t("code"),
                    name: "codesnippet.code",
                    value: this.data.actions.codesnippetCode
                },{
                    xtype:'combo',
                    fieldLabel: t('element_css_selector'),
                    name: "codesnippet.selector",
                    disableKeyFilter: true,
                    store: [["body","body"],["head","head"]],
                    triggerAction: "all",
                    mode: "local",
                    width: 250,
                    value: this.data.actions.codesnippetSelector
                },{
                    xtype:'combo',
                    fieldLabel: t('insert_position'),
                    name: "codesnippet.position",
                    store: [["beginning",t("beginning")],["end",t("end")],["replace",t("replace")]],
                    triggerAction: "all",
                    typeAhead: false,
                    editable: false,
                    forceSelection: true,
                    mode: "local",
                    width: 250,
                    value: this.data.actions.codesnippetPosition
                }]
            }, {
                xtype: "fieldset",
                itemId: "actions_persona",
                title: t('associate_target_group') + " (" + t("personas") + ")",
                collapsible: true,
                collapsed: !this.data.actions.personaEnabled,
                items: [{
                    xtype: "combo",
                    name: "persona.id",
                    displayField:'text',
                    valueField: "id",
                    store: pimcore.globalmanager.get("personas"),
                    editable: false,
                    width: 300,
                    triggerAction: 'all',
                    listWidth: 200,
                    mode: "local",
                    value: this.data.actions.personaId,
                    emptyText: t("select_a_persona")
                }]
            }]
        });

        return this.actionsForm;
    },

    getSettings: function () {

        this.settingsForm = new Ext.form.FormPanel({
            layout: "pimcoreform",
            title: t("settings"),
            bodyStyle: "padding:10px;",
            autoScroll: true,
            border:false,
            items: [{
                xtype: "textfield",
                fieldLabel: t("name"),
                name: "name",
                width: 250,
                disabled: true,
                value: this.data.name
            }, {
                name: "description",
                fieldLabel: t("description"),
                xtype: "textarea",
                width: 400,
                height: 100,
                value: this.data.description
            }, {
                name: "scope",
                fieldLabel: t("scope"),
                xtype: "combo",
                width: 200,
                value: this.data["scope"],
                mode: "local",
                triggerAction: "all",
                store: [["user", t("user")],["session", t("session")], ["hit", t("hit")]]
            }, {
                name: "active",
                fieldLabel: t("active"),
                xtype: "checkbox",
                checked: this.data["active"]
            }]
        });

        return this.settingsForm;
    },

    getConditions: function() {
        var addMenu = [];
        var itemTypes = Object.keys(pimcore.settings.targeting.conditions);
        for(var i=0; i<itemTypes.length; i++) {
            if(itemTypes[i].indexOf("item") == 0) {
                addMenu.push({
                    iconCls: "pimcore_icon_add",
                    handler: this.addCondition.bind(this, itemTypes[i]),
                    text: pimcore.settings.targeting.conditions[itemTypes[i]](null, null,true)
                });
            }
        }

        this.conditionsContainer = new Ext.Panel({
            title: t("conditions"),
            autoScroll: true,
            forceLayout: true,
            tbar: [{
                iconCls: "pimcore_icon_add",
                menu: addMenu
            }],
            border: false
        });

        return this.conditionsContainer;
    },

    addCondition: function (type, data) {

        var item = pimcore.settings.targeting.conditions[type](this, data);

        // add logic for brackets
        var tab = this;
        item.on("afterrender", function (el) {
            el.getEl().applyStyles({position: "relative", "min-height": "40px"});
            var leftBracket = el.getEl().insertHtml("beforeEnd",
                '
(
', true);
            var rightBracket = el.getEl().insertHtml("beforeEnd",
                '
)
', true);

            if(data["bracketLeft"]){
                leftBracket.addClass("pimcore_targeting_bracket_active");
            }
            if(data["bracketRight"]){
                rightBracket.addClass("pimcore_targeting_bracket_active");
            }

            // open
            leftBracket.on("click", function (ev, el) {
                var bracket = Ext.get(el);
                bracket.toggleClass("pimcore_targeting_bracket_active");

                tab.recalculateBracketIdent(tab.conditionsContainer.items);
            });

            // close
            rightBracket.on("click", function (ev, el) {
                var bracket = Ext.get(el);
                bracket.toggleClass("pimcore_targeting_bracket_active");

                tab.recalculateBracketIdent(tab.conditionsContainer.items);
            });

            // make ident
            tab.recalculateBracketIdent(tab.conditionsContainer.items);
        });

        this.conditionsContainer.add(item);
        item.doLayout();
        this.conditionsContainer.doLayout();

        this.currentIndex++;

        this.recalculateButtonStatus();
    },

    save: function () {

        var saveData = {};
        saveData["settings"] = this.settingsForm.getForm().getFieldValues();
        saveData["actions"] = this.actionsForm.getForm().getFieldValues();
        saveData["actions"]["redirect.enabled"] = !this.actionsForm.getComponent("actions_redirect").collapsed;
        saveData["actions"]["event.enabled"] = !this.actionsForm.getComponent("actions_event").collapsed;
        saveData["actions"]["codesnippet.enabled"] = !this.actionsForm.getComponent("actions_codesnippet").collapsed;
        saveData["actions"]["persona.enabled"] = !this.actionsForm.getComponent("actions_persona").collapsed;
        saveData["actions"]["programmatically.enabled"] = !this.actionsForm.getComponent("actions_programmatically")
                                                                                .collapsed;

        var conditionsData = [];
        var condition, tb, operator;
        var conditions = this.conditionsContainer.items.getRange();
        for (var i=0; i<conditions.length; i++) {
            condition = conditions[i].getForm().getFieldValues();

            // get the operator (AND, OR, AND_NOT)
            tb = conditions[i].getTopToolbar();
            if (tb.getComponent("toggle_or").pressed) {
                operator = "or";
            } else if (tb.getComponent("toggle_and_not").pressed) {
                operator = "and_not";
            } else {
                operator = "and";
            }
            condition["operator"] = operator;

            // get the brackets
            condition["bracketLeft"] = Ext.get(conditions[i].getEl().query(".pimcore_targeting_bracket_left")[0])
                                                                .hasClass("pimcore_targeting_bracket_active");
            condition["bracketRight"] = Ext.get(conditions[i].getEl().query(".pimcore_targeting_bracket_right")[0])
                                                                .hasClass("pimcore_targeting_bracket_active");

            conditionsData.push(condition);
        }
        saveData["conditions"] = conditionsData;

        Ext.Ajax.request({
            url: "/admin/reports/targeting/rule-save",
            params: {
                id: this.data.id,
                data: Ext.encode(saveData)
            },
            method: "post",
            success: function () {

            }.bind(this)
        });
    },

    recalculateButtonStatus: function () {
        var conditions = this.conditionsContainer.items.getRange();
        var tb;
        for (var i=0; i<conditions.length; i++) {
            tb = conditions[i].getTopToolbar();
            if(i==0) {
                tb.getComponent("toggle_and").hide();
                tb.getComponent("toggle_or").hide();
                tb.getComponent("toggle_and_not").hide();
            } else {
                tb.getComponent("toggle_and").show();
                tb.getComponent("toggle_or").show();
                tb.getComponent("toggle_and_not").show();
            }
        }
    },

    /**
     * make ident for bracket
     * @param list
     */
    recalculateBracketIdent: function(list) {
        var ident = 0, lastIdent = 0, margin = 20;
        var colors = ["transparent","#007bff", "#00ff99", "#e1a6ff", "#ff3c00", "#000000"];

        list.each(function (condition) {

            // only rendered conditions
            if(condition.rendered == false)
                return;

            // html from this condition
            var item = condition.getEl();

            // apply ident margin
            item.applyStyles({
                "margin-left": margin * ident + "px",
                "margin-right": margin * ident + "px"
            });

            // apply colors
            if(ident > 0)
                item.applyStyles({
                    "border-left": "1px solid " + colors[ident],
                    "border-right": "1px solid " + colors[ident],
                    "padding": "0px 1px"
                });
            else
                item.applyStyles({
                    "border-left": "0px",
                    "border-right": "0px"
                });

            // apply specials :-)
            if(ident == 0) {
                item.applyStyles({
                    "margin-top": "10px"
                });
            } else if(ident == lastIdent) {
                item.applyStyles({
                    "margin-top": "0px",
                    "margin-bottom": "0px",
                    "padding": "1px"
                });
            } else {
                item.applyStyles({
                    "margin-top": "5px"
                });
            }

            // remeber current ident
            lastIdent = ident;

            // check if a bracket is open
            if(item.select('.pimcore_targeting_bracket_left.pimcore_targeting_bracket_active').getCount() == 1)
            {
                ident++;
            }
            // check if a bracket is close
            else if(item.select('.pimcore_targeting_bracket_right.pimcore_targeting_bracket_active').getCount() == 1)
            {
                if(ident > 0)
                    ident--;
            }
        });
    }
});

<|endoftext|>


<commit_before>app.controller('addModalController', ["$scope", "$uibModalInstance", "fields", "title", function($scope, $uibModalInstance, fields, title) {
	$scope.fields = fields;
	$scope.title = title;
	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

  	$scope.ok = function () {
  		var result = {};
  		for (var i = 0; i < $scope.fields.length; i++) {
  			result[$scope.fields[i].var_name] = $scope.fields[i].value;
  		}
    	$uibModalInstance.close(result);
  	};
}]);<commit_msg>add default dates to timepickers to avoid not a number error<commit_after>app.controller('addModalController', ["$scope", "$uibModalInstance", "fields", "title", function($scope, $uibModalInstance, fields, title) {
	var cur_date = new Date();

  for (var i = 0; i < fields.length; i++) {
    if (fields[i].type == "timepicker") {
      fields[i].value = cur_date;
    }
  }

  $scope.fields = fields;
	$scope.title = title;
	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

  $scope.time_change = function (val){
    console.log(val);
  }

  	$scope.ok = function () {
  		var result = {};
  		for (var i = 0; i < $scope.fields.length; i++) {
  			result[$scope.fields[i].var_name] = $scope.fields[i].value;
  		}
    	$uibModalInstance.close(result);
  	};
}]);<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign, camelcase */

import axios from 'axios';
import parse from 'date-fns/parse';
import isPast from 'date-fns/is_past';

import { MultiplePersonsError, NoPersonsError } from '../../errors';
import { PORTAL_API_URL } from '../../constants';

/*
  Add some convenience fields to our API response to make
  conditionals easier throughout the app.
*/
function addFields(data) {
  const {
    is_recurring_donor,
    membership_expiration_date,
    membership_level,
    never_given,
    is_mdev,
    is_current_circle,
    is_former_circle,
  } = data;

  let membershipLevel;
  let isExpired;

  const isSingleDonor =
    !never_given &&
    !is_recurring_donor &&
    !!membership_expiration_date &&
    !is_mdev;

  const isRecurringDonor =
    is_recurring_donor &&
    !!membership_expiration_date &&
    !is_mdev &&
    !is_current_circle &&
    !is_former_circle;

  const isCircleDonor =
    (is_current_circle || is_former_circle) && !!membership_expiration_date;

  const isCustomDonor =
    (is_mdev && !is_current_circle && !is_former_circle) ||
    (!never_given && !membership_expiration_date);

  if (membership_expiration_date) {
    isExpired = isPast(parse(membership_expiration_date));
  } else {
    isExpired = null;
  }

  if (membership_level) {
    membershipLevel = membership_level.toLowerCase();
  } else {
    membershipLevel = null;
  }

  delete data.is_mdev;
  delete data.is_former_circle;
  delete data.is_current_circle;

  return {
    ...data,
    is_single_donor: isSingleDonor,
    is_recurring_donor: isRecurringDonor,
    is_circle_donor: isCircleDonor,
    is_custom_donor: isCustomDonor,
    is_expired: isExpired,
    membership_level: membershipLevel,
  };
}

function createDefaultState() {
  return { details: {} };
}

const MUTATION_TYPES = {
  setDetails: 'SET_DETAILS',
};

const mutations = {
  [MUTATION_TYPES.setDetails](state, details) {
    state.details = details;
  },
};

const actions = {
  getOtherUser: async ({ commit, rootState }, email) => {
    const { accessToken } = rootState.tokenUser;
    const { data } = await axios.get(`${PORTAL_API_URL}persons/`, {
      params: { email },
      headers: { Authorization: `Bearer ${accessToken}` },
    });

    if (!data.length) throw new NoPersonsError();
    if (data.length > 1) throw new MultiplePersonsError();

    commit(MUTATION_TYPES.setDetails, addFields(data[0]));
  },

  getUser: async ({ commit, rootState }) => {
    const { accessToken } = rootState.tokenUser;
    const { data } = await axios.get(`${PORTAL_API_URL}self/`, {
      headers: { Authorization: `Bearer ${accessToken}` },
    });

    commit(MUTATION_TYPES.setDetails, addFields(data));
  },
};

export default {
  namespaced: true,
  state: createDefaultState(),
  mutations,
  actions,
  getters: {},
};
<commit_msg>better comment<commit_after>/* eslint-disable no-param-reassign, camelcase */

import axios from 'axios';
import parse from 'date-fns/parse';
import isPast from 'date-fns/is_past';

import { MultiplePersonsError, NoPersonsError } from '../../errors';
import { PORTAL_API_URL } from '../../constants';

function addFields(data) {
  const {
    is_recurring_donor,
    membership_expiration_date,
    membership_level,
    never_given,
    is_mdev,
    is_current_circle,
    is_former_circle,
  } = data;
  let membershipLevel;
  let isExpired;

  const isSingleDonor =
    !never_given &&
    !is_recurring_donor &&
    !!membership_expiration_date &&
    !is_mdev;

  const isRecurringDonor =
    is_recurring_donor &&
    !!membership_expiration_date &&
    !is_mdev &&
    !is_current_circle &&
    !is_former_circle;

  const isCircleDonor =
    (is_current_circle || is_former_circle) && !!membership_expiration_date;

  const isCustomDonor =
    (is_mdev && !is_current_circle && !is_former_circle) ||
    (!never_given && !membership_expiration_date);

  if (membership_expiration_date) {
    isExpired = isPast(parse(membership_expiration_date));
  } else {
    isExpired = null;
  }

  if (membership_level) {
    membershipLevel = membership_level.toLowerCase();
  } else {
    membershipLevel = null;
  }

  delete data.is_mdev;
  delete data.is_former_circle;
  delete data.is_current_circle;

  // The following booleans are mutually exclusive:
  // is_single_donor, is_recurring_donor, is_circle_donor, is_custom_donor
  // the first three are guaranteed to have a string expiration date
  // all are guaranteed to have never_given: false

  return {
    ...data,
    is_single_donor: isSingleDonor,
    is_recurring_donor: isRecurringDonor,
    is_circle_donor: isCircleDonor,
    is_custom_donor: isCustomDonor,
    is_expired: isExpired,
    membership_level: membershipLevel,
  };
}

function createDefaultState() {
  return { details: {} };
}

const MUTATION_TYPES = {
  setDetails: 'SET_DETAILS',
};

const mutations = {
  [MUTATION_TYPES.setDetails](state, details) {
    state.details = details;
  },
};

const actions = {
  getOtherUser: async ({ commit, rootState }, email) => {
    const { accessToken } = rootState.tokenUser;
    const { data } = await axios.get(`${PORTAL_API_URL}persons/`, {
      params: { email },
      headers: { Authorization: `Bearer ${accessToken}` },
    });

    if (!data.length) throw new NoPersonsError();
    if (data.length > 1) throw new MultiplePersonsError();

    commit(MUTATION_TYPES.setDetails, addFields(data[0]));
  },

  getUser: async ({ commit, rootState }) => {
    const { accessToken } = rootState.tokenUser;
    const { data } = await axios.get(`${PORTAL_API_URL}self/`, {
      headers: { Authorization: `Bearer ${accessToken}` },
    });

    commit(MUTATION_TYPES.setDetails, addFields(data));
  },
};

export default {
  namespaced: true,
  state: createDefaultState(),
  mutations,
  actions,
  getters: {},
};
<|endoftext|>


<commit_before>var request = new XMLHttpRequest();
request.open('GET', 'https://spark-assets.netlify.com/spark-core-icons.svg');
request.send();
request.onload = function () {
  document.querySelector('#sprk-icons').innerHTML = this.response;
  window.dispatchEvent(new CustomEvent('sprk-icons-loaded', {
    bubbles: true, detail: new Date(),
  }));
};
<commit_msg>adding IE11 safe code for icon load event<commit_after>var request = new XMLHttpRequest();
request.open('GET', 'https://spark-assets.netlify.com/spark-core-icons.svg');
request.send();
request.onload = function () {
  document.querySelector('#sprk-icons').innerHTML = this.response;
  let event;
  if (typeof (Event) === 'function') {
    event = new Event('sprk-icons-loaded');
  } else {
    event = document.createEvent('Event');
    event.initEvent('sprk-icons-loaded', true, true);
  }

  window.dispatchEvent(event);
};
<|endoftext|>


<commit_before>import { selected } from "../selectors"
import { submissionCloneFunc } from "./submission-clone"

import { clone } from "../../../lib/cloneutils"
import Promise from "bluebird"

const submissionClone = submissionCloneFunc(clone)
// PUBLIC: Async thunk action for cloning all selected submissions.
export const submissionCloneAll = () => {
  return (dispatch, getState) => {
    const selectedSubmissions = selected(getState())
    return Promise.map(selectedSubmissions, submission => {
      return dispatch(submissionClone(submission))
    },
    {concurrency: 5})
  }
}
<commit_msg>drop concurrency to 3, need to dynamically set in the future<commit_after>import { selected } from "../selectors"
import { submissionCloneFunc } from "./submission-clone"

import { clone } from "../../../lib/cloneutils"
import Promise from "bluebird"

const submissionClone = submissionCloneFunc(clone)
// PUBLIC: Async thunk action for cloning all selected submissions.
export const submissionCloneAll = () => {
  return (dispatch, getState) => {
    const selectedSubmissions = selected(getState())
    return Promise.map(selectedSubmissions, submission => {
      return dispatch(submissionClone(submission))
    },
    // TODO: dynamically set this based on system
    {concurrency: 3})
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
 * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
 * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
 * obligations to provide maintenance, support, updates, enhancements or
 * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
 * liable to any party for direct, indirect, special, incidental or
 * consequential damages, including lost profits, arising out of the use of this
 * software and its documentation, even if Memorial Sloan-Kettering Cancer
 * Center has been advised of the possibility of such damage.
 */

/*
 * This file is part of cBioPortal.
 *
 * cBioPortal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Created by suny1 on 11/18/15.
 */

var ccPlots = (function (Plotly, _, $) {

    var study_ids = [], mrna_profiles = [], profile_data = {};

    var fetch_profile_data = function(_queried_study_ids) {

        var _param_mrna_profile_arr = _.map(_queried_study_ids, function(_study_id) { return _study_id + "_rna_seq_v2_mrna"});
        var _param_mut_profile_arr = _.map(_queried_study_ids, function(_study_id) { return _study_id + "_mutations"});

        var params = {
            genes: ["SOX9"],
            genetic_profile_ids: _param_mrna_profile_arr.concat(_param_mut_profile_arr)
        };

        window.cbioportal_client.getGeneticProfileData(params).then(
            function(_result) {
                profile_data = _result;
                study_ids = _.uniq(_.pluck(_result, "study_id"));
                mrna_profiles =  _.map(study_ids, function(_study_id) { return _study_id + "_rna_seq_v2_mrna"});
                render();
            });

    }

    var render = function() {

        var data = [];

        //merge genomic profile data into mutation profile data for mutated samples
        var _mut_data = _.filter(profile_data, function(_obj) { return _obj.hasOwnProperty("mutation_status"); });
        var _tmp_profile_group = _.filter(profile_data, function(_obj) { return !(_obj.hasOwnProperty("mutation_status")); }); //profile data only
        _.each(_tmp_profile_group, function(_profile_obj) {
            var mutation_type = "non";
            var mutation_details = "";
            _.each(_mut_data, function(_mut_obj) {
                if (_profile_obj.study_id === _mut_obj.study_id &&
                    _profile_obj.sample_id === _mut_obj.sample_id) {
                    mutation_type = _mut_obj.mutation_type; //TODO: set a priority list for mutation type
                    mutation_details += _mut_obj.amino_acid_change + ", ";
                }
            });
            _profile_obj.mutation_type = mutation_type;
            _profile_obj.mutation_details = mutation_details.substring(0, mutation_details.length - 2);
        });

        //separate groups
        var _non_mut_group = _.filter(_tmp_profile_group, function(_obj) { return _obj.mutation_type === "non"; });
        var _mix_mut_group = _.filter(_tmp_profile_group, function(_obj) { return _obj.mutation_type !== "non"; });

        // ---- define tracks ----
        // no mutation
        var non_mut_track = {
            x: _.map(_.pluck(_non_mut_group, "study_id"), function(_study_id){ return study_ids.indexOf(_study_id) + Math.random() * 0.3 - 0.15; }),
            y: _.pluck(_non_mut_group, "profile_data"),
            mode: 'markers',
            type: 'scatter',
            name: 'No Mutation',
            marker: {
                color: '#00AAF8',
                size: 5,
                line: {color: '#0089C6', width: 1.2}
            },
            hoverinfo: "x+y"
        };
        data.push(non_mut_track);

        //mutated tracks
        var _mut_types = _.uniq(_.pluck(_mix_mut_group, "mutation_type"));
        _.each(_mut_types, function(_mut_type) {
            var _mut_group = _.filter(_mix_mut_group, function(_obj) { return _obj.mutation_type === _mut_type; });
            var _mut_track = {
                x: _.map(_.pluck(_mut_group, "study_id"), function(_study_id){ return study_ids.indexOf(_study_id) + Math.random() * 0.3 - 0.15; }),
                y: _.pluck(_mut_group, "profile_data"),
                mode: 'markers',
                type: 'scatter',
                name: _mut_type,
                marker: {
                    color: '#1C1C1C',
                    size: 6,
                    line: {color: '#B40404', width: 1.2}
                },
                hoverinfo: "x+y"
            };
            data.push(_mut_track);
        });

        //box plots
        _.each(mrna_profiles, function(_profile_id) {
            var _box = {
                y: _.pluck(_.filter(_non_mut_group, function(_result_obj) { return _result_obj.genetic_profile_id == _profile_id; }), "profile_data"),
                x0: mrna_profiles.indexOf(_profile_id),
                type: 'box',
                opacity: 0.6,
                marker: {
                    color: 'grey',
                    size: 7
                },
                line: { width: 1},
                boxpoints: false,
                showlegend: false
            };
            data.push(_box);
        });

                //var _mut_mixed_group = _.filter(_result, function(_result_obj) { return _result_obj.hasOwnProperty("mutation_status"); });

                ////categorize mutations
                ////TODO: join for cases with multiple mutations
                //var _mut_groups = {};
                //_.each(_mut_mixed_group, function(_mut_obj) {
                //    if (!_mut_groups.hasOwnProperty(_mut_obj.mutation_type)) {
                //        _mut_groups[_mut_obj.mutation_type] = [];
                //    }
                //    _mut_groups[_mut_obj.mutation_type].push(_mut_obj);
                //});
                //
                ////get profile data for mutated cases
                //_.each(_mut_mixed_group, function(_mut_obj) {
                //    _.each(_non_mut_group, function(_non_mut_obj) {
                //        if (_non_mut_obj.sample_id === _mut_obj.sample_id) {
                //            _mut_obj.profile_data = _non_mut_obj.profile_data;
                //        }
                //    });
                //});

                ////remove all the mutated cases from non-mut group
                ////TODO: numbers doesn't match, check again
                //_non_mut_group = _.filter(_non_mut_group, function(_result_obj) { return ($.inArray( _result_obj.sample_id, _.pluck(_mut_mixed_group, "sample_id")) == -1); });

                //$.each(Object.keys(_mut_groups), function(_index, _mut_type) {
                //
                //    var shapes = ['diamond', 'triangle-down', 'circle', 'pentagon', 'square'];
                //    var _mut_group = _mut_groups[_mut_type];
                //
                //    var _mut_track = {
                //        x: _.map(_.pluck(_mut_group, "study_id"), function(_study_id){ return study_arr.indexOf(_study_id) + Math.random() * 0.3 - 0.15; }),
                //        y: _.pluck(_mut_group, "profile_data"),
                //        mode: 'markers',
                //        type: 'scatter',
                //        name: _mut_group[0].mutation_type,
                //        marker: {
                //            size: 10,
                //            symbol: shapes[_index],
                //            color: '#FF3333'
                //        }
                //    };
                //    data.push(_mut_track);
                //});

        // ---- define layout ----
        var vals = [];
        for (var i = 0 ; i < mrna_profiles.length; i++) {
            vals.push(i);
        }
        var layout = {
            margin: {
                t: 20,
                b: 200,
                l: 100
            },
            xaxis: {
                tickmode: "array",
                ticktext: study_ids,
                tickvals: vals,
                tickangle: 45
            },
            yaxis: {
                range: [ Math.min(_.pluck(profile_data, "profile_data")), Math.max(_.pluck(profile_data, "profile_data")) ],
                title: 'SOX9 Expression -- RNA Seq V2'
            }
        };

        Plotly.newPlot('cc_plots_box', data, layout);

    }

    return {
        init: function() {

            var tmp = setInterval(function () {timer();}, 1000);
            function timer() {
                if (window.studies !== undefined) {
                    clearInterval(tmp);
                    $("#cc_plots_box").empty();
                    fetch_profile_data(_.pluck(_.pluck(window.studies.models, "attributes"), "studyId"));
                }
            }

        }
    }

}(window.Plotly, window._, window.jQuery));

<commit_msg>parsed mutation data by types<commit_after>/*
 * Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
 * FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
 * is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
 * obligations to provide maintenance, support, updates, enhancements or
 * modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
 * liable to any party for direct, indirect, special, incidental or
 * consequential damages, including lost profits, arising out of the use of this
 * software and its documentation, even if Memorial Sloan-Kettering Cancer
 * Center has been advised of the possibility of such damage.
 */

/*
 * This file is part of cBioPortal.
 *
 * cBioPortal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Created by suny1 on 11/18/15.
 */

var ccPlots = (function (Plotly, _, $) {

    var study_ids = [], study_meta = [], mrna_profiles = [], profile_data = {};

    var fetch_profile_data = function(_queried_study_ids) {

        var _param_mrna_profile_arr = _.map(_queried_study_ids, function(_study_id) { return _study_id + "_rna_seq_v2_mrna"});
        var _param_mut_profile_arr = _.map(_queried_study_ids, function(_study_id) { return _study_id + "_mutations"});

        var _get_genetic_profile_params = {
            genes: ["SOX9"],
            genetic_profile_ids: _param_mrna_profile_arr.concat(_param_mut_profile_arr)
        };

        window.cbioportal_client.getGeneticProfileData(_get_genetic_profile_params).then(
            function(_result) {
                profile_data = _result;
                study_ids = _.uniq(_.pluck(_result, "study_id"));
                mrna_profiles =  _.map(study_ids, function(_study_id) { return _study_id + "_rna_seq_v2_mrna"});

                var _get_study_params = {
                    study_ids : study_ids
                };
                window.cbioportal_client.getStudies(_get_study_params).then(
                    function(_study_meta) {
                        study_meta = _study_meta;
                        render();
                    }
                );
            });

    }

    var render = function() {

        var data = [];

        //merge genomic profile data into mutation profile data for mutated samples
        var _mut_data = _.filter(profile_data, function(_obj) { return _obj.hasOwnProperty("mutation_status"); });
        var _tmp_profile_group = _.filter(profile_data, function(_obj) { return !(_obj.hasOwnProperty("mutation_status")); }); //profile data only
        _.each(_tmp_profile_group, function(_profile_obj) {
            var mutation_type = "non";
            var mutation_details = "";
            _.each(_mut_data, function(_mut_obj) {
                if (_profile_obj.study_id === _mut_obj.study_id &&
                    _profile_obj.sample_id === _mut_obj.sample_id) {
                    mutation_type = _mut_obj.mutation_type; //TODO: set a priority list for mutation type
                    mutation_details += _mut_obj.amino_acid_change + ", ";
                }
            });
            _profile_obj.mutation_type = mutation_type;
            _profile_obj.mutation_details = mutation_details.substring(0, mutation_details.length - 2);
        });

        //separate groups
        var _non_mut_group = _.filter(_tmp_profile_group, function(_obj) { return _obj.mutation_type === "non"; });
        var _mix_mut_group = _.filter(_tmp_profile_group, function(_obj) { return _obj.mutation_type !== "non"; });

        console.log(_non_mut_group);
        console.log(_mix_mut_group);

        // ---- define tracks ----
        // no mutation
        var non_mut_track = {
            x: _.map(_.pluck(_non_mut_group, "study_id"), function(_study_id){ return study_ids.indexOf(_study_id) + Math.random() * 0.3 - 0.15; }),
            y: _.pluck(_non_mut_group, "profile_data"),
            mode: 'markers',
            type: 'scatter',
            name: 'No Mutation',
            text: _.pluck(_non_mut_group, "sample_id"),
            marker: {
                color: '#00AAF8',
                size: 5,
                line: {color: '#0089C6', width: 1.2}
            },
            hoverinfo: "y+text"
        };
        data.push(non_mut_track);

        //mutated tracks
        var _mut_shapes = ["triangle-up", "diamond", "cross", "square", "triangle-down", "pentagon", "hourglass"],
            _mut_colors = ["#DF7401", "#1C1C1C", "#DF7401", "#1C1C1C", "#DF7401", "#1C1C1C", "#DF7401"];
        var _mut_types = _.uniq(_.pluck(_mix_mut_group, "mutation_type"));
        $.each(_mut_types, function(_index, _mut_type) {
            var _mut_group = _.filter(_mix_mut_group, function(_obj) { return _obj.mutation_type === _mut_type; });
            var _mut_track = {
                x: _.map(_.pluck(_mut_group, "study_id"), function(_study_id){ return study_ids.indexOf(_study_id) + Math.random() * 0.3 - 0.15; }),
                y: _.pluck(_mut_group, "profile_data"),
                mode: 'markers',
                type: 'scatter',
                name: _mut_type,
                marker: {
                    color: _mut_colors[_index],
                    size: 6,
                    line: {color: '#B40404', width: 1.2},
                    symbol: _mut_shapes[_index]
                },
                hoverinfo: "x+y"
            };
            data.push(_mut_track);
        });

        //box plots
        _.each(mrna_profiles, function(_profile_id) {
            var _box = {
                y: _.pluck(_.filter(_non_mut_group, function(_result_obj) { return _result_obj.genetic_profile_id == _profile_id; }), "profile_data"),
                x0: mrna_profiles.indexOf(_profile_id),
                type: 'box',
                opacity: 0.6,
                marker: {
                    color: 'grey',
                    size: 7
                },
                line: { width: 1},
                boxpoints: false,
                showlegend: false
            };
            data.push(_box);
        });

        // ---- define layout ----
        var vals = [];
        for (var i = 0 ; i < mrna_profiles.length; i++) {
            vals.push(i);
        }
        var layout = {
            margin: {
                t: 20,
                b: 200,
                l: 100
            },
            xaxis: {
                tickmode: "array",
                ticktext: _.pluck(study_meta, "short_name"),
                tickvals: vals,
                tickangle: 45
            },
            yaxis: {
                range: [ Math.min(_.pluck(profile_data, "profile_data")), Math.max(_.pluck(profile_data, "profile_data")) ],
                title: 'SOX9 Expression -- RNA Seq V2'
            }
        };

        Plotly.newPlot('cc_plots_box', data, layout);

    }

    return {
        init: function() {

            var tmp = setInterval(function () {timer();}, 1000);
            function timer() {
                if (window.studies !== undefined) {
                    clearInterval(tmp);
                    $("#cc_plots_box").empty();
                    fetch_profile_data(_.pluck(_.pluck(window.studies.models, "attributes"), "studyId"));
                }
            }

        }
    }

}(window.Plotly, window._, window.jQuery));

<|endoftext|>


<commit_before>cur_frm.cscript.refresh = function(doc, dt, dn) {
	if(!doc.__islocal) {
		var field_list = ['lead', 'customer', 'supplier', 'contact', 'opportunity',
			'quotation', 'support_ticket'];
		var hide_list = [];
		$.each(field_list, function(i, v) {
			if(!doc[v]) hide_list.push(v);
		});

		if(hide_list.length < field_list.length) hide_field(hide_list);
	}
}

cur_frm.cscript.make_communication_body = function() {
	var communication_wrapper = cur_frm.fields_dict.communication_html.wrapper;
	communication_wrapper.innerHTML = '';
	cur_frm.communication_html = $a(communication_wrapper, 'div');
	$(cur_frm.communication_html).css({
		'min-height': '275px',
	});
}

cur_frm.cscript.render_communication_list = function(doc, dt, dn) {
	var ListView = wn.views.ListView.extend({
		init: function(doclistview) {
			this._super(doclistview);
			this.fields = this.fields.concat([
				"`tabCommunication`.communication_date",
				"`tabCommunication`.category",
				"`tabCommunication`.subject",
				"`tabCommunication`.content"
			]);
			this.order_by = "`tabCommunication`.communication_date desc";
		},

		prepare_data: function(data) {
			this._super(data);
			data.creation = wn.datetime.str_to_user(data.communication_date);

			data.content = cstr(data.subject) + " | " + cstr(data.content);

			if(data.content && data.content.length > 50) {
				data.content = '' +
					data.description.substr(0,50) + '...';
			}

		},

		columns: [
			{width: '3%', content: 'docstatus'},
			{width: '15%', content: 'name'},
			{width: '15%', content: 'category'},
			{width: '55%', content: 'content'},
			{width: '12%', content:'communication_date',
				css: {'text-align': 'right', 'color':'#777'}}
		],

	});

	cur_frm.cscript.render_list(doc, 'Communication', cur_frm.communication_html,
		ListView, function(doctype) {
			var new_doc = LocalDB.create(doctype);
			new_doc = locals[doctype][new_doc];
			new_doc[doc.doctype.toLowerCase()] = doc.name;
			loaddoc(new_doc.doctype, new_doc.name);
		});
}

// Render List
cur_frm.cscript.render_list = function(doc, doctype, wrapper, ListView, make_new_doc) {
	wn.model.with_doctype(doctype, function(r) {
		if(r) {
			return;
		}
		var RecordListView = wn.views.RecordListView.extend({
			default_docstatus: ['0', '1', '2'],
			default_filters: [
				[doctype, doc.doctype.toLowerCase(), '=', doc.name],
			],
		});

		if (make_new_doc) {
			RecordListView = RecordListView.extend({
				make_new_doc: make_new_doc,
			});
		}

		var record_list_view = new RecordListView(doctype, wrapper, ListView);
	});
}<commit_msg>fix in communication listing<commit_after>cur_frm.cscript.refresh = function(doc, dt, dn) {
	if(!doc.__islocal) {
		var field_list = ['lead', 'customer', 'supplier', 'contact', 'opportunity',
			'quotation', 'support_ticket'];
		var hide_list = [];
		$.each(field_list, function(i, v) {
			if(!doc[v]) hide_list.push(v);
		});

		if(hide_list.length < field_list.length) hide_field(hide_list);
	}
}

cur_frm.cscript.make_communication_body = function() {
	var communication_wrapper = cur_frm.fields_dict.communication_html.wrapper;
	communication_wrapper.innerHTML = '';
	cur_frm.communication_html = $a(communication_wrapper, 'div');
	$(cur_frm.communication_html).css({
		'min-height': '275px',
	});
}

cur_frm.cscript.render_communication_list = function(doc, dt, dn) {
	var ListView = wn.views.ListView.extend({
		init: function(doclistview) {
			this._super(doclistview);
			this.fields = this.fields.concat([
				"`tabCommunication`.communication_date",
				"`tabCommunication`.category",
				"`tabCommunication`.subject",
				"`tabCommunication`.content"
			]);
			this.order_by = "`tabCommunication`.communication_date desc";
		},

		prepare_data: function(data) {
			this._super(data);
			data.creation = wn.datetime.str_to_user(data.communication_date);

			data.content = cstr(data.subject) + " | " + cstr(data.content);

			if(data.content && data.content.length > 50) {
				data.content = '' +
					data.description.substr(0,50) + '...';
			}

		},

		columns: [
			{width: '3%', content: 'docstatus'},
			{width: '15%', content: 'name'},
			{width: '15%', content: 'category'},
			{width: '55%', content: 'content'},
			{width: '12%', content:'communication_date',
				css: {'text-align': 'right', 'color':'#777'}}
		],

	});

	cur_frm.cscript.render_list(doc, 'Communication', cur_frm.communication_html,
		ListView, function(doctype) {
			var new_doc = LocalDB.create(doctype);
			new_doc = locals[doctype][new_doc];
			new_doc[doc.doctype.toLowerCase()] = doc.name;
			loaddoc(new_doc.doctype, new_doc.name);
		});
}

// Render List
cur_frm.cscript.render_list = function(doc, doctype, wrapper, ListView, make_new_doc) {
	wn.model.with_doctype(doctype, function(r) {
		if((r && r['403']) || wn.boot.profile.all_read.indexOf(doctype)===-1) {
			return;
		}
		var RecordListView = wn.views.RecordListView.extend({
			default_docstatus: ['0', '1', '2'],
			default_filters: [
				[doctype, doc.doctype.toLowerCase(), '=', doc.name],
			],
		});

		if (make_new_doc) {
			RecordListView = RecordListView.extend({
				make_new_doc: make_new_doc,
			});
		}

		var record_list_view = new RecordListView(doctype, wrapper, ListView);
	});
}<|endoftext|>