<commit_before>import generateUUID from './../src/client/uuid.js';
import boundEval from './../src/client/bound-eval.js';
import Morph from "./Morph.js"

let loadPromise = undefined;

export default class LivelyCodeMirror extends HTMLElement {

  static get codeMirrorPath() {
     return  "src/external/code-mirror/"
  }

  static async loadModule(path) {
    return lively.loadJavaScriptThroughDOM("codemirror_"+path.replace(/[^A-Za-z]/g,""),
      this.codeMirrorPath + path) //
  }

  static async loadCSS(path) {
    return lively.loadCSSThroughDOM("codemirror_" + path.replace(/[^A-Za-z]/g,""),
       this.codeMirrorPath + path)
  }

  static async loadModules() {
    if (loadPromise) return loadPromise

    loadPromise = (async () => {
      await this.loadModule("lib/codemirror.js")

      await this.loadModule("mode/javascript/javascript.js")
      await this.loadModule("mode/markdown/markdown.js")
      await this.loadModule("mode/htmlmixed/htmlmixed.js")

      await this.loadModule("addon/mode/overlay.js")
      await this.loadModule("mode/gfm/gfm.js")

      await this.loadModule("addon/hint/show-hint.js")
      await this.loadModule("addon/hint/javascript-hint.js")
      await this.loadModule("addon/search/searchcursor.js")
      await this.loadModule("addon/search/search.js")
      await this.loadModule("addon/comment/comment.js")
      await this.loadModule("addon/search/jump-to-line.js")
      await this.loadModule("addon/dialog/dialog.js")
      await this.loadModule("keymap/sublime.js")
      await System.import(lively4url + '/templates/lively-code-mirror-hint.js')

      this.loadCSS("addon/hint/show-hint.css")
      this.loadCSS("../../../templates/lively-code-mirror.css")
    })()
    return loadPromise
  }

  initialize() {
  	this._attrObserver = new MutationObserver((mutations) => {
	  mutations.forEach((mutation) => {
        if(mutation.type == "attributes") {
          // console.log("observation", mutation.attributeName,mutation.target.getAttribute(mutation.attributeName));
          this.attributeChangedCallback(
            mutation.attributeName,
            mutation.oldValue,
            mutation.target.getAttribute(mutation.attributeName))
        }
      });
    });
    this._attrObserver.observe(this, { attributes: true });
  }

  applyAttribute(attr) {
    var value =this.getAttribute(attr)
    if (value !== undefined) {
      this.setAttribute(attr, value)
    }
  }

  async attachedCallback() {
    if (this.isLoading || this.editor ) return;
    this.isLoading = true
    this.root = this.shadowRoot // used in code mirror to find current element

    var text = this.childNodes[0];
    var container = this.container;
    var element = this;

    await LivelyCodeMirror.loadModules()

    var value
    if (this.textContent) {
      value = this.decodeHTML(this.textContent);
    } else {
      value = this.value || "";
    }

    this.editor = CodeMirror(this.shadowRoot.querySelector("#code-mirror-container"), {
      value: value,
      lineNumbers: true,
      gutters: ["leftgutter", "CodeMirror-linenumbers", "rightgutter"]
    });
    // mode: {name: "javascript", globalVars: true},

    if (this.mode) {
      this.editor.setOption("mode", this.mode);
    }

    this.editor.setOption("keyMap",  "sublime")
	this.editor.setOption("extraKeys", {
      "Alt-F": "findPersistent",
      // "Ctrl-F": "search",
      "Ctrl-F": (cm) => {
		// something immediately grabs the "focus" and we close the search dialog..
        // #Hack...
        setTimeout(() => {
            this.editor.execCommand("findPersistent")
            this.shadowRoot.querySelector(".CodeMirror-search-field").focus()
        }, 10)
        // this.editor.execCommand("find")
      },
      "Ctrl-/": "toggleCommentIndented",
      "Ctrl-Space": "autocomplete",
      "Ctrl-P": (cm) => {
          let text = this.getSelectionOrLine()
          this.tryBoundEval(text, true);
      },
      "Ctrl-D": (cm) => {
          let text = this.getSelectionOrLine()
          this.tryBoundEval(text, false);
      },
      "Ctrl-S": (cm) => {
        this.doSave(this.editor.getValue());
      },
    });
    this.editor.setOption("hintOptions", {
      container: this.shadowRoot.querySelector("#code-mirror-hints")
    });

    this.editor.on("change", evt => this.dispatchEvent(new CustomEvent("change", {detail: evt})))
    this.isLoading = false
    this.dispatchEvent(new CustomEvent("editor-loaded"))

	// apply attributes
    _.map(this.attributes, ea => ea.name).forEach(ea => this.applyAttribute(ea))
  };

   // Fires when an attribute was added, removed, or updated
  attributeChangedCallback(attr, oldVal, newVal) {
    if(!this.editor){
        return false;
    }
    switch(attr){
      // case "theme":
      //     this.editor.setTheme( newVal );
      //     break;
      // case "mode":
      //     this.changeMode( newVal );
      //     break;
      // case "fontsize":
      //     this.editor.setFontSize( newVal );
      //     break;
      // case "softtabs":
      //     this.editor.getSession().setUseSoftTabs( newVal );
      //     break;
      case "tabsize":
		this.setOption("tabSize", newVal)
        break;
      // case "readonly":
      //     this.editor.setReadOnly( newVal );
      //     break;
      case "wrapmode":
        this.setOption("lineWrapping", newVal)
      	break;
    }
  }

  setOption(name, value) {
	if (!this.editor) return; // we loose...
    this.editor.setOption(name, value)
  }

  doSave(text) {
    this.tryBoundEval(text) // just a default implementation...
  }

  getSelectionOrLine() {
    var text = this.editor.getSelection()
    if (text.length > 0)
      return text
    else
      return this.editor.getLine(this.editor.getCursor("end").line)
  }

  getDoitContext() {
    return this.doitContext
  }

  setDoitContext(context) {
    return this.doitContext = context;
  }

  getTargetModule() {
    return this.targetModule;
  }

  setTargetModule(module) {
    return this.targetModule = module;
  }

  async boundEval(str, context) {
    // Ensure target module loaded (for .js files only)
    // TODO: duplicate with var recorder plugin
    const MODULE_MATCHER = /.js$/;
    if(MODULE_MATCHER.test(this.getTargetModule())) {
      await System.import(this.getTargetModule())
    }

    // src, topLevelVariables, thisReference, <- finalStatement
    return boundEval(str, this.getDoitContext(), this.getTargetModule());
  }

  printResult(result) {
    var editor = this.editor;
    var text = result
    this.editor.setCursor(this.editor.getCursor("end"))
    // don't replace existing selection
    this.editor.replaceSelection(result, "around")

  }

 async tryBoundEval(str, printResult) {
    var resp;
    resp = await this.boundEval(str, this.getDoitContext())
    if (resp.isError) {
      var e = resp.value
      console.error(e)
      if (printResult) {
        window.LastError = e
        this.printResult("" +e)
      } else {
        lively.handleError(e)
      }
      return e
    }
    var result = resp.value
    var obj2string = function(obj) {
      var s = "";
      try {
        s += obj // #HACK some objects cannot be printed any more
      } catch(e) {
        s += "UnprintableObject["+ Object.keys(e) + "]" // so we print something else
      }
      return s
    }

    if (printResult) {
      // alaways wait on promises.. when interactively working...
      if (result && result.then) {
        // we will definitly return a promise on which we can wait here
        result
          .then( result => {
            this.printResult("RESOLVED: " + obj2string(result))
          })
          .catch( error => {
            console.error(error);
            // window.LastError = error;
            this.printResult("Error in Promise: \n" +error)
          })
      } else {
        this.printResult(" " + obj2string(result))
        if (result instanceof HTMLElement ) {
          lively.showElement(result)
        }
      }
    }
    return result
  }

  async inspectIt(str) {
    var result =  await this.boundEval(str, this.getDoitContext())
    if (!result.isError) {
      lively.openInspector(result.value, null, str)
    }
  }

  doSave(text) {
    this.tryBoundEval(text) // just a default implementation...
  }

  detachedCallback() {
    this._attached = false;
  };

  get value() {
    if (this.editor) {
      return this.editor.getValue()
    } else {
      return this._value
    }
  }

  set value(text) {
    if (this.editor) {
      this.editor.setValue(text)
    } else {
      this._value = text
    }
  }

  setCustomStyle(source) {
    this.shadowRoot.querySelector("#customStyle").textContent = source
  }

  getCustomStyle(source) {
    return this.shadowRoot.querySelector("#customStyle").textContent
  }

  encodeHTML(s) {
    return s.replace("&", "&").replace("<", "<")
  }

  decodeHTML(s) {
    return s.replace("<", "<").replace("&", "&")
  }

  resize() {
    // #ACE Component compatiblity
  }

  enableAutocompletion() {
    // #ACE Component compatiblity
  }

  changeModeForFile(filename) {

    // lively.notify("change mode for file:" + this.editor)
    // #ACE Component compatiblity

    if (!this.editor) return;

    var mode = "text"
    // #TODO there must be some kind of automatching?
    if (filename.match(/\.html$/)) {
      mode = "htmlmixed"
    } else if (filename.match(/\.md$/)) {
      mode = "gfm"
    } else if (filename.match(/\.js$/)) {
      mode = "javascript"
    }
    this.mode = mode
    this.editor.setOption("mode", mode)
  }

  livelyPrepareSave() {
    this.textContent = this.encodeHTML(this.editor.getValue())
  }

  livelyPreMigrate() {
    this.lastScrollInfo = this.editor.getScrollInfo(); // #Example #PreserveContext
  }

  async livelyMigrate(other) {
    this.addEventListener("editor-loaded", () => {
        this.value = other.value
      	this.editor.scrollTo(other.lastScrollInfo.left, other.lastScrollInfo.top)
    })
  }

  find(name) {
    // #TODO this is horrible... Why is there not a standard method for this?
	if (!this.editor) return;
    var found = false;
  	this.value.split("\n").forEach((ea, index) => {
      if (!found && (ea.indexOf(name) != -1)) {
	    this.editor.setCursor(index, 10000);// line end ;-)
        this.editor.focus()
        found = ea;
  	  }
    })
  }
}

// LivelyCodeMirror.loadModules()

<commit_msg>code mirror bracket matching and closing<commit_after>import generateUUID from './../src/client/uuid.js';
import boundEval from './../src/client/bound-eval.js';
import Morph from "./Morph.js"

let loadPromise = undefined;

export default class LivelyCodeMirror extends HTMLElement {

  static get codeMirrorPath() {
     return  "src/external/code-mirror/"
  }

  static async loadModule(path) {
    return lively.loadJavaScriptThroughDOM("codemirror_"+path.replace(/[^A-Za-z]/g,""),
      this.codeMirrorPath + path) //
  }

  static async loadCSS(path) {
    return lively.loadCSSThroughDOM("codemirror_" + path.replace(/[^A-Za-z]/g,""),
       this.codeMirrorPath + path)
  }

  static async loadModules() {
    if (loadPromise) return loadPromise

    loadPromise = (async () => {
      await this.loadModule("lib/codemirror.js")

      await this.loadModule("mode/javascript/javascript.js")
      await this.loadModule("mode/markdown/markdown.js")
      await this.loadModule("mode/htmlmixed/htmlmixed.js")

      await this.loadModule("addon/mode/overlay.js")
      await this.loadModule("mode/gfm/gfm.js")

      await this.loadModule("addon/edit/matchbrackets.js")
      await this.loadModule("addon/edit/closetag.js")
      await this.loadModule("addon/edit/closebrackets.js")
      await this.loadModule("addon/edit/continuelist.js")
      await this.loadModule("addon/edit/matchtags.js")
      await this.loadModule("addon/edit/trailingspace.js")

      await this.loadModule("addon/hint/show-hint.js")
      await this.loadModule("addon/hint/javascript-hint.js")
      await this.loadModule("addon/search/searchcursor.js")
      await this.loadModule("addon/search/search.js")
      await this.loadModule("addon/comment/comment.js")
      await this.loadModule("addon/search/jump-to-line.js")
      await this.loadModule("addon/dialog/dialog.js")
      await this.loadModule("keymap/sublime.js")
      await System.import(lively4url + '/templates/lively-code-mirror-hint.js')

      this.loadCSS("addon/hint/show-hint.css")
      this.loadCSS("../../../templates/lively-code-mirror.css")
    })()
    return loadPromise
  }

  initialize() {
  	this._attrObserver = new MutationObserver((mutations) => {
	  mutations.forEach((mutation) => {
        if(mutation.type == "attributes") {
          // console.log("observation", mutation.attributeName,mutation.target.getAttribute(mutation.attributeName));
          this.attributeChangedCallback(
            mutation.attributeName,
            mutation.oldValue,
            mutation.target.getAttribute(mutation.attributeName))
        }
      });
    });
    this._attrObserver.observe(this, { attributes: true });
  }

  applyAttribute(attr) {
    var value =this.getAttribute(attr)
    if (value !== undefined) {
      this.setAttribute(attr, value)
    }
  }

  async attachedCallback() {
    if (this.isLoading || this.editor ) return;
    this.isLoading = true
    this.root = this.shadowRoot // used in code mirror to find current element

    var text = this.childNodes[0];
    var container = this.container;
    var element = this;

    await LivelyCodeMirror.loadModules()

    var value
    if (this.textContent) {
      value = this.decodeHTML(this.textContent);
    } else {
      value = this.value || "";
    }

    this.editor = CodeMirror(this.shadowRoot.querySelector("#code-mirror-container"), {
      value: value,
      lineNumbers: true,
      gutters: ["leftgutter", "CodeMirror-linenumbers", "rightgutter"]
    });
    // mode: {name: "javascript", globalVars: true},

    if (this.mode) {
      this.editor.setOption("mode", this.mode);
    }

    // edit addons
    this.editor.setOption("showTrailingSpace", true)
    // this.editor.setOption("matchTags", true)
    this.editor.setOption("matchBrackets", true)

    this.editor.setOption("matchBrackets", true)
    this.editor.setOption("autoCloseBrackets", true)
    this.editor.setOption("autoCloseTags", true)

    this.editor.setOption("keyMap",  "sublime")
	this.editor.setOption("extraKeys", {
      "Alt-F": "findPersistent",
      // "Ctrl-F": "search",
      "Ctrl-F": (cm) => {
		// something immediately grabs the "focus" and we close the search dialog..
        // #Hack...
        setTimeout(() => {
            this.editor.execCommand("findPersistent")
            this.shadowRoot.querySelector(".CodeMirror-search-field").focus()
        }, 10)
        // this.editor.execCommand("find")
      },
      "Ctrl-/": "toggleCommentIndented",
      "Ctrl-Space": "autocomplete",
      "Ctrl-P": (cm) => {
          let text = this.getSelectionOrLine()
          this.tryBoundEval(text, true);
      },
      "Ctrl-D": (cm) => {
          let text = this.getSelectionOrLine()
          this.tryBoundEval(text, false);
      },
      "Ctrl-S": (cm) => {
        this.doSave(this.editor.getValue());
      },
    });
    this.editor.setOption("hintOptions", {
      container: this.shadowRoot.querySelector("#code-mirror-hints")
    });

    this.editor.on("change", evt => this.dispatchEvent(new CustomEvent("change", {detail: evt})))
    this.isLoading = false
    this.dispatchEvent(new CustomEvent("editor-loaded"))

	// apply attributes
    _.map(this.attributes, ea => ea.name).forEach(ea => this.applyAttribute(ea))
  };

   // Fires when an attribute was added, removed, or updated
  attributeChangedCallback(attr, oldVal, newVal) {
    if(!this.editor){
        return false;
    }
    switch(attr){
      // case "theme":
      //     this.editor.setTheme( newVal );
      //     break;
      // case "mode":
      //     this.changeMode( newVal );
      //     break;
      // case "fontsize":
      //     this.editor.setFontSize( newVal );
      //     break;
      // case "softtabs":
      //     this.editor.getSession().setUseSoftTabs( newVal );
      //     break;
      case "tabsize":
		this.setOption("tabSize", newVal)
        break;
      // case "readonly":
      //     this.editor.setReadOnly( newVal );
      //     break;
      case "wrapmode":
        this.setOption("lineWrapping", newVal)
      	break;
    }
  }

  setOption(name, value) {
	if (!this.editor) return; // we loose...
    this.editor.setOption(name, value)
  }

  doSave(text) {
    this.tryBoundEval(text) // just a default implementation...
  }

  getSelectionOrLine() {
    var text = this.editor.getSelection()
    if (text.length > 0)
      return text
    else
      return this.editor.getLine(this.editor.getCursor("end").line)
  }

  getDoitContext() {
    return this.doitContext
  }

  setDoitContext(context) {
    return this.doitContext = context;
  }

  getTargetModule() {
    return this.targetModule;
  }

  setTargetModule(module) {
    return this.targetModule = module;
  }

  async boundEval(str, context) {
    // Ensure target module loaded (for .js files only)
    // TODO: duplicate with var recorder plugin
    const MODULE_MATCHER = /.js$/;
    if(MODULE_MATCHER.test(this.getTargetModule())) {
      await System.import(this.getTargetModule())
    }

    // src, topLevelVariables, thisReference, <- finalStatement
    return boundEval(str, this.getDoitContext(), this.getTargetModule());
  }

  printResult(result) {
    var editor = this.editor;
    var text = result
    this.editor.setCursor(this.editor.getCursor("end"))
    // don't replace existing selection
    this.editor.replaceSelection(result, "around")

  }

 async tryBoundEval(str, printResult) {
    var resp;
    resp = await this.boundEval(str, this.getDoitContext())
    if (resp.isError) {
      var e = resp.value
      console.error(e)
      if (printResult) {
        window.LastError = e
        this.printResult("" +e)
      } else {
        lively.handleError(e)
      }
      return e
    }
    var result = resp.value
    var obj2string = function(obj) {
      var s = "";
      try {
        s += obj // #HACK some objects cannot be printed any more
      } catch(e) {
        s += "UnprintableObject["+ Object.keys(e) + "]" // so we print something else
      }
      return s
    }

    if (printResult) {
      // alaways wait on promises.. when interactively working...
      if (result && result.then) {
        // we will definitly return a promise on which we can wait here
        result
          .then( result => {
            this.printResult("RESOLVED: " + obj2string(result))
          })
          .catch( error => {
            console.error(error);
            // window.LastError = error;
            this.printResult("Error in Promise: \n" +error)
          })
      } else {
        this.printResult(" " + obj2string(result))
        if (result instanceof HTMLElement ) {
          lively.showElement(result)
        }
      }
    }
    return result
  }

  async inspectIt(str) {
    var result =  await this.boundEval(str, this.getDoitContext())
    if (!result.isError) {
      lively.openInspector(result.value, null, str)
    }
  }

  doSave(text) {
    this.tryBoundEval(text) // just a default implementation...
  }

  detachedCallback() {
    this._attached = false;
  };

  get value() {
    if (this.editor) {
      return this.editor.getValue()
    } else {
      return this._value
    }
  }

  set value(text) {
    if (this.editor) {
      this.editor.setValue(text)
    } else {
      this._value = text
    }
  }

  setCustomStyle(source) {
    this.shadowRoot.querySelector("#customStyle").textContent = source
  }

  getCustomStyle(source) {
    return this.shadowRoot.querySelector("#customStyle").textContent
  }

  encodeHTML(s) {
    return s.replace("&", "&").replace("<", "<")
  }

  decodeHTML(s) {
    return s.replace("<", "<").replace("&", "&")
  }

  resize() {
    // #ACE Component compatiblity
  }

  enableAutocompletion() {
    // #ACE Component compatiblity
  }

  changeModeForFile(filename) {

    // lively.notify("change mode for file:" + this.editor)
    // #ACE Component compatiblity

    if (!this.editor) return;

    var mode = "text"
    // #TODO there must be some kind of automatching?
    if (filename.match(/\.html$/)) {
      mode = "htmlmixed"
    } else if (filename.match(/\.md$/)) {
      mode = "gfm"
    } else if (filename.match(/\.js$/)) {
      mode = "javascript"
    }
    this.mode = mode
    this.editor.setOption("mode", mode)
  }

  livelyPrepareSave() {
    this.textContent = this.encodeHTML(this.editor.getValue())
  }

  livelyPreMigrate() {
    this.lastScrollInfo = this.editor.getScrollInfo(); // #Example #PreserveContext
  }

  async livelyMigrate(other) {
    this.addEventListener("editor-loaded", () => {
        this.value = other.value
      	this.editor.scrollTo(other.lastScrollInfo.left, other.lastScrollInfo.top)
    })
  }

  find(name) {
    // #TODO this is horrible... Why is there not a standard method for this?
	if (!this.editor) return;
    var found = false;
  	this.value.split("\n").forEach((ea, index) => {
      if (!found && (ea.indexOf(name) != -1)) {
	    this.editor.setCursor(index, 10000);// line end ;-)
        this.editor.focus()
        found = ea;
  	  }
    })
  }
}

// LivelyCodeMirror.loadModules()

<|endoftext|>


<commit_before>'use strict'

angular.module('antismash.ui.bacterial.as_start', ['ngFileUpload'])
    .controller('AsStartCtrl', ['$state', '$window', 'Upload',
        function ($state, $window, Upload) {
            var vm = this;

            vm.valid_endings = '.gbk,.gb,.gbff,.emb,.embl,.fa,.fasta,.fna';
            vm.valid_gff_endings = '.gff,.gff3';

            // Defaullt values
            vm.submission = {
                jobtype: 'antismash6',
            };
            vm.extra_features = [
                { id: 'knownclusterblast', description: 'KnownClusterBlast', default: true, legacy: true},
                { id: 'clusterblast', description: 'ClusterBlast', default: false, legacy: true },
                { id: 'subclusterblast', description: 'SubClusterBlast', default: true, legacy: true },
                { id: 'asf', description: 'ActiveSiteFinder', default: true, legacy: true },
                { id: 'rre', description: 'RREFinder', default: true },
                { id: 'clusterhmmer', description: 'Cluster Pfam analysis', default: false },
                { id: 'pfam2go', description: 'Pfam-based GO term annotation', default: false },
            ];

            for (var i = 0; i < vm.extra_features.length; i++) {
                var feature = vm.extra_features[i];
                vm.submission[feature.id] = feature.default;
            }

            vm.strictness_levels = [
                { id: 'strict', description: 'Detects well-defined clusters containing all required parts.' },
                { id: 'relaxed', description: 'Detects partial clusters missing one or more functional parts.' },
                { id: 'loose', description: 'Detects poorly-defined clusters and clusters that likely match primary metabolites.',
                  warning: 'Likely to cause false positives.' },
            ];

            vm.hmmdetection_strictness = 1;

            vm.genefinder = 'prodigal';

            vm.submit = function (form) {
                vm.active_submission = true;
                vm.errror_message = null;

                if (vm.upload_file) {
                    vm.submission.seq = vm.file;
                    if (vm.gff_file) {
                        vm.submission.gff3 = vm.gff_file;
                        vm.submission.genefinder = 'none';
                    } else {
                        vm.submission.genefinder = 'prodigal';
                    }
                } else {
                    vm.submission.ncbi = vm.ncbi;
                }

                if (vm.email) {
                    vm.submission.email = vm.email;
                }

                vm.submission.hmmdetection_strictness = vm.strictness_levels[vm.hmmdetection_strictness].id;

                Upload.upload({
                    url: '/api/v1.0/submit',
                    data: vm.submission,
                }).then(function (resp) {
                    vm.active_submission = false;
                    $state.go('show.job', { id: resp.data.id });
                }, function (resp) {
                    vm.active_submission = false;
                    var full_message = "Job submission failed.";
                    if (resp.data.message) {
                        full_message += " The error message was: " + resp.data.message;
                    }
                    vm.error_message = full_message;
                    console.log(resp);
                }, function (evt) {
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    if (!evt.config.data.seq) {
                        return;
                    }
                    console.log('progress: ' + progressPercentage + '% ' + evt.config.data.seq.name);
                });
            }

            vm.isFastaFile = function (filename) {
                var FASTA_ENDINGS = ['.fa', '.fna', '.fasta'];

                // IE can't do endsWith()
                if (!String.prototype.endsWith) {
                    String.prototype.endsWith = function(search_string, position) {
                        var subject = this.toString();
                        if (typeof position !== 'number' || !isFinite(postion) || Math.floor(postion) !== postion || postion > subject.length) {
                            postion = subject.length;
                        }
                        position -= search_string.length;
                        var last_index = filename.lastIndexOf(search_string);
                        return last_index !== -1 && last_index === position;
                    }
                }

                for (var i in FASTA_ENDINGS) {
                    var ending = FASTA_ENDINGS[i];
                    if (filename.toLowerCase().endsWith(ending)) {
                        return true;
                    }
                }
                return false;
            }

            vm.showGffInput = function () {
                return vm.showGeneFinder();
            }

            vm.showGeneFinder = function () {
                if (!vm.upload_file) {
                    return false;
                }

                if (!vm.file || !vm.file.name) {
                    return false;
                }

                return vm.isFastaFile(vm.file.name);
            }

            vm.validJob = function () {
                if (vm.upload_file) {
                    if (!vm.file) {
                        return false;
                    }
                } else {
                    if (!vm.ncbi) {
                        return false;
                    }
                }
                return true;
            }

            vm.allOff = function () {
                for (var i = 0; i < vm.extra_features.length; i++) {
                    var feature = vm.extra_features[i];
                    vm.submission[feature.id] = false;
                }
            }

            vm.allOn = function () {
                for (var i = 0; i < vm.extra_features.length; i++) {
                    var feature = vm.extra_features[i];
                    vm.submission[feature.id] = true;
                }
            }

            vm.loadSampleInput = function () {
                vm.upload_file = false;
                vm.ncbi = "Y16952";
            }

            vm.openSampleOutput = function () {
                $window.location.href = "/upload/example/index.html";
            }

            vm.loadJob = function () {
                console.log(vm.job_id);
                if (vm.job_id.substr(0, 8).toLowerCase() == 'bacteria') {
                    $state.go('show.job', { id: vm.job_id });
                }
                else if (vm.job_id.substr(0, 5).toLowerCase() == 'fungi') {
                    $window.location.href = "http://fungismash.secondarymetabolites.org/#!/show/job/" + vm.job_id;
                }
                else if (vm.job_id.substr(0, 6).toLowerCase() == 'plants') {
                    $window.location.href = "http://plantismash.secondarymetabolites.org/#!/show/job/" + vm.job_id;
                }
                $state.go('show.job', { id: vm.job_id });
            }

            vm.clearGff = function () {
                vm.gff_file = null;
            }

            vm.strictness_descriptions = function () {
                var descriptions = [];
                for (var i = 0; i <= vm.hmmdetection_strictness; i++) {
                    descriptions.push(vm.strictness_levels[i].description);
                }
                return descriptions;
            }
        }]);
<commit_msg>start: Add support for tigrfam and cc_mibig options<commit_after>'use strict'

angular.module('antismash.ui.bacterial.as_start', ['ngFileUpload'])
    .controller('AsStartCtrl', ['$state', '$window', 'Upload',
        function ($state, $window, Upload) {
            var vm = this;

            vm.valid_endings = '.gbk,.gb,.gbff,.emb,.embl,.fa,.fasta,.fna';
            vm.valid_gff_endings = '.gff,.gff3';

            // Defaullt values
            vm.submission = {
                jobtype: 'antismash6',
            };
            vm.extra_features = [
                { id: 'knownclusterblast', description: 'KnownClusterBlast', default: true, legacy: true},
                { id: 'clusterblast', description: 'ClusterBlast', default: false, legacy: true },
                { id: 'subclusterblast', description: 'SubClusterBlast', default: true, legacy: true },
                { id: 'cc_mibig', description: 'MIBiG cluster comparison', default: false },
                { id: 'asf', description: 'ActiveSiteFinder', default: true, legacy: true },
                { id: 'rre', description: 'RREFinder', default: true },
                { id: 'clusterhmmer', description: 'Cluster Pfam analysis', default: false },
                { id: 'pfam2go', description: 'Pfam-based GO term annotation', default: false },
                { id: 'tigrfam', description: 'TIGRFam analysis', default: false },
            ];

            for (var i = 0; i < vm.extra_features.length; i++) {
                var feature = vm.extra_features[i];
                vm.submission[feature.id] = feature.default;
            }

            vm.strictness_levels = [
                { id: 'strict', description: 'Detects well-defined clusters containing all required parts.' },
                { id: 'relaxed', description: 'Detects partial clusters missing one or more functional parts.' },
                { id: 'loose', description: 'Detects poorly-defined clusters and clusters that likely match primary metabolites.',
                  warning: 'Likely to cause false positives.' },
            ];

            vm.hmmdetection_strictness = 1;

            vm.genefinder = 'prodigal';

            vm.submit = function (form) {
                vm.active_submission = true;
                vm.errror_message = null;

                if (vm.upload_file) {
                    vm.submission.seq = vm.file;
                    if (vm.gff_file) {
                        vm.submission.gff3 = vm.gff_file;
                        vm.submission.genefinder = 'none';
                    } else {
                        vm.submission.genefinder = 'prodigal';
                    }
                } else {
                    vm.submission.ncbi = vm.ncbi;
                }

                if (vm.email) {
                    vm.submission.email = vm.email;
                }

                vm.submission.hmmdetection_strictness = vm.strictness_levels[vm.hmmdetection_strictness].id;

                Upload.upload({
                    url: '/api/v1.0/submit',
                    data: vm.submission,
                }).then(function (resp) {
                    vm.active_submission = false;
                    $state.go('show.job', { id: resp.data.id });
                }, function (resp) {
                    vm.active_submission = false;
                    var full_message = "Job submission failed.";
                    if (resp.data.message) {
                        full_message += " The error message was: " + resp.data.message;
                    }
                    vm.error_message = full_message;
                    console.log(resp);
                }, function (evt) {
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    if (!evt.config.data.seq) {
                        return;
                    }
                    console.log('progress: ' + progressPercentage + '% ' + evt.config.data.seq.name);
                });
            }

            vm.isFastaFile = function (filename) {
                var FASTA_ENDINGS = ['.fa', '.fna', '.fasta'];

                // IE can't do endsWith()
                if (!String.prototype.endsWith) {
                    String.prototype.endsWith = function(search_string, position) {
                        var subject = this.toString();
                        if (typeof position !== 'number' || !isFinite(postion) || Math.floor(postion) !== postion || postion > subject.length) {
                            postion = subject.length;
                        }
                        position -= search_string.length;
                        var last_index = filename.lastIndexOf(search_string);
                        return last_index !== -1 && last_index === position;
                    }
                }

                for (var i in FASTA_ENDINGS) {
                    var ending = FASTA_ENDINGS[i];
                    if (filename.toLowerCase().endsWith(ending)) {
                        return true;
                    }
                }
                return false;
            }

            vm.showGffInput = function () {
                return vm.showGeneFinder();
            }

            vm.showGeneFinder = function () {
                if (!vm.upload_file) {
                    return false;
                }

                if (!vm.file || !vm.file.name) {
                    return false;
                }

                return vm.isFastaFile(vm.file.name);
            }

            vm.validJob = function () {
                if (vm.upload_file) {
                    if (!vm.file) {
                        return false;
                    }
                } else {
                    if (!vm.ncbi) {
                        return false;
                    }
                }
                return true;
            }

            vm.allOff = function () {
                for (var i = 0; i < vm.extra_features.length; i++) {
                    var feature = vm.extra_features[i];
                    vm.submission[feature.id] = false;
                }
            }

            vm.allOn = function () {
                for (var i = 0; i < vm.extra_features.length; i++) {
                    var feature = vm.extra_features[i];
                    vm.submission[feature.id] = true;
                }
            }

            vm.loadSampleInput = function () {
                vm.upload_file = false;
                vm.ncbi = "Y16952";
            }

            vm.openSampleOutput = function () {
                $window.location.href = "/upload/example/index.html";
            }

            vm.loadJob = function () {
                console.log(vm.job_id);
                if (vm.job_id.substr(0, 8).toLowerCase() == 'bacteria') {
                    $state.go('show.job', { id: vm.job_id });
                }
                else if (vm.job_id.substr(0, 5).toLowerCase() == 'fungi') {
                    $window.location.href = "http://fungismash.secondarymetabolites.org/#!/show/job/" + vm.job_id;
                }
                else if (vm.job_id.substr(0, 6).toLowerCase() == 'plants') {
                    $window.location.href = "http://plantismash.secondarymetabolites.org/#!/show/job/" + vm.job_id;
                }
                $state.go('show.job', { id: vm.job_id });
            }

            vm.clearGff = function () {
                vm.gff_file = null;
            }

            vm.strictness_descriptions = function () {
                var descriptions = [];
                for (var i = 0; i <= vm.hmmdetection_strictness; i++) {
                    descriptions.push(vm.strictness_levels[i].description);
                }
                return descriptions;
            }
        }]);
<|endoftext|>


<commit_before>'use strict';

const joi = require('joi');

const countSchema = joi
    .object()
    .options({ stripUnknown: true })
    .keys({
        yes: joi
            .number()
            .min(0)
            .default(0),
        no: joi
            .number()
            .min(0)
            .default(0),
        variants: joi.object({
            arg: joi.string(),
            value: joi.number().min(0),
        }),
    });

const clientMetricsSchema = joi
    .object()
    .options({ stripUnknown: true })
    .keys({
        appName: joi.string().required(),
        instanceId: joi.string().required(),
        bucket: joi
            .object()
            .required()
            .keys({
                start: joi.date().required(),
                stop: joi.date().required(),
                toggles: joi.object().pattern(/.*/, countSchema),
            }),
    });

module.exports = { clientMetricsSchema };
<commit_msg>fix: metric-schema for variant counts<commit_after>'use strict';

const joi = require('joi');

const countSchema = joi
    .object()
    .options({ stripUnknown: true })
    .keys({
        yes: joi
            .number()
            .min(0)
            .default(0),
        no: joi
            .number()
            .min(0)
            .default(0),
        variants: joi.object().pattern(joi.string(), joi.number().min(0)),
    });

const clientMetricsSchema = joi
    .object()
    .options({ stripUnknown: true })
    .keys({
        appName: joi.string().required(),
        instanceId: joi.string().required(),
        bucket: joi
            .object()
            .required()
            .keys({
                start: joi.date().required(),
                stop: joi.date().required(),
                toggles: joi.object().pattern(/.*/, countSchema),
            }),
    });

module.exports = { clientMetricsSchema };
<|endoftext|>


<commit_before>if (!window.MapEntity) window.MapEntity = {};

$(document).ready(function (e) {

    // Scrollable panels
    var fillmax = function () {
        $('.scrollable').each(function () {
            if ($(window).width() >= 992) {
                var top = $(this).offset().top,
                    height = $(window).height() - top - parseFloat($(this).css('margin-top'))
                                                      - parseFloat($(this).css('margin-bottom'));
                $(this).css('max-height', height + 'px');
            } else {
                $(this).css('max-height', 'none')
            }
        });
    };

    setTimeout(fillmax, 0);
    $(window).resize(fillmax);

    // Chosen-ify elements
    $(".chzn-select").chosen();

    // Top-navigation tabs
    MapEntity.history.render();

    // Fade out success/infos messages
    $('#alert-box .alert').delay(2000).fadeOut('slow');

    // Form Cancel buttons
    $('#button-id-cancel').click(function (){ window.history.go(-1); });

    // Auto-hide elements
    $('.autohide').parents().hover(
        function() { $(this).children(".autohide").addClass('hover'); },
        function() { $(this).children(".autohide").removeClass('hover'); }
    );

    // Views
    var context = $('body').data();
    console.debug('View ', context.modelname, context.viewname);
    $(window).trigger('entity:view:' + context.viewname, [context]);

    // Maps
    $(window).on('map:init', function (e) {
        var data = e.originalEvent ?
                   e.originalEvent.detail : e.detail;
        $.extend(data, context);
        $(window).trigger('entity:map', [data]);
        $(window).trigger('entity:map:' + context.viewname, [data]);

        // Split
        $("#panelleft").resizable({
            handleSelector: ".splitter",
            resizeHeight: false,
            onDragEnd: function (e, $el, opt) {
                window.maps[0].invalidateSize();
            }
        });
        $(".details-panel").resizable({
            handleSelector: ".splitter",
            resizeHeight: false,
            onDragEnd: function (e, $el, opt) {
                window.maps[0].invalidateSize();
            }
        });
    });

});
<commit_msg>Use resizable options<commit_after>if (!window.MapEntity) window.MapEntity = {};

$(document).ready(function (e) {

    // Scrollable panels
    var fillmax = function () {
        $('.scrollable').each(function () {
            if ($(window).width() >= 992) {
                var top = $(this).offset().top,
                    height = $(window).height() - top - parseFloat($(this).css('margin-top'))
                                                      - parseFloat($(this).css('margin-bottom'));
                $(this).css('max-height', height + 'px');
            } else {
                $(this).css('max-height', 'none')
            }
        });
    };

    setTimeout(fillmax, 0);
    $(window).resize(fillmax);

    // Chosen-ify elements
    $(".chzn-select").chosen();

    // Top-navigation tabs
    MapEntity.history.render();

    // Fade out success/infos messages
    $('#alert-box .alert').delay(2000).fadeOut('slow');

    // Form Cancel buttons
    $('#button-id-cancel').click(function (){ window.history.go(-1); });

    // Auto-hide elements
    $('.autohide').parents().hover(
        function() { $(this).children(".autohide").addClass('hover'); },
        function() { $(this).children(".autohide").removeClass('hover'); }
    );

    // Views
    var context = $('body').data();
    console.debug('View ', context.modelname, context.viewname);
    $(window).trigger('entity:view:' + context.viewname, [context]);

    // Maps
    $(window).on('map:init', function (e) {
        var data = e.originalEvent ?
                   e.originalEvent.detail : e.detail;
        $.extend(data, context);
        $(window).trigger('entity:map', [data]);
        $(window).trigger('entity:map:' + context.viewname, [data]);

        // Split
        var resizableOptions = {
            handleSelector: ".splitter",
            resizeHeight: false,
            onDragEnd: function (e, $el, opt) {
                window.maps[0].invalidateSize();
            }
        }
        $("#panelleft").resizable(resizableOptions);
        $(".details-panel").resizable(resizableOptions);
    });

});
<|endoftext|>


<commit_before>/*
     Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

             http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
*/

"use strict";

var compilerInternals = require('./compiler-internals'),
    platform = require('./platform-bootstrap/node/platform'),
    fs = require('fs'),
    vm = require('vm'),
    SourceNode = require('source-map').SourceNode,
    assert = require('assert'),
    util = require('../util');

var scxmlToScjson = compilerInternals.scxmlToScjson,
    scjsonToModule = compilerInternals.scjsonToModule,
    scJsonAnalyzer = compilerInternals.scJsonAnalyzer;

/**
 * Compile the raw scxml document into a compiled JS module
 * Top-level scripts are extracted so that they can be compiled and executed independently
 * @memberof scxml
 * @param  {string}   url       The url of the scxml document
 * @param  {string}   docString The raw scxml document to be parsed
 * @param  {modelCallback} cb        The callback to invoke once the document has been parsed
 * @param  {HostContext}   [hostContext]   Context provided by the interpreter host
 */
function documentStringToModel(url,docString,cb,hostContext){
    if (typeof hostContext !== 'object' || hostContext === null) {
        hostContext = {};
    }

    var scJson = scxmlToScjson(docString);

    scJsonAnalyzer.analyze(scJson, url, hostContext, function (result) {
        if (result.errors.length) {
            cb(result.errors);
            return;
        };

        createModule(url, result.scJson, hostContext, cb);
    });
}

/**
 * Compile the generated scxml module and any embedded or external scripts
 * @param  {string}   docUrl        The scxml document url
 * @param  {SCJsonRawModule}   rawModule      The raw SCION module created by scjson-to-module
 * @param  {HostContext}   [hostContext]   Context provided by the interpreter host
 * @param  {function} cb            Callback to invoke with the compiled module or an error
 * @private
 */
function compileModule(docUrl, rawModule, hostContext, cb) {
    const promiseOffset = 2;
    let invokeConstructorPromises = [];
    //TODO: modules need to be evaluated in order of dependencies. we need to test recursive invoke content.
    for(let invokeConstructor of rawModule.invokeConstructors.reverse()){

      let rootScripts = invokeConstructor.rootScripts;
      let scriptCount = rootScripts.length;
      let promises = new Array(scriptCount + promiseOffset);

      for (var i = 0; i < scriptCount; i++) {
          var curScript = rootScripts[i];
          if (curScript.src) {
              // defer the fetch until ModelFactoryFactory.prepare
              promises[i+promiseOffset] = Promise.resolve(curScript);
          } else {
              promises[i+promiseOffset] = new Promise(function(resolve, reject) {
                  try {
                      var content = curScript.content;
                      delete curScript.content;
                      var compiledScript = platform.module.compileScript(content, {
                          filename: docUrl,
                          lineOffset: curScript.$line,
                          columnOffset: curScript.$column
                      });
                      curScript.compiled = compiledScript;
                      resolve(curScript);
                  } catch(e) {
                      reject(e);
                  }
              });
          }
      }

      promises[0] = new Promise(function(resolve, reject) {
          try {
              var compiledModule = platform.module.compileScript('(' + invokeConstructor.module + ')', {
                  filename: docUrl
              });

              resolve(compiledModule);
          } catch(e) {
              reject(e);
          }
      });

      promises[1] = new Promise(function(resolve, reject) {
          if (!invokeConstructor.datamodel) {
              resolve(undefined);
          } else {
              try {
                  var compiledDatamodel = platform.module.compileScript(invokeConstructor.datamodel, {
                      filename: docUrl
                  });

                  resolve(compiledDatamodel);
              } catch(e) {
                  reject(e);
              }
          }
      })

      invokeConstructorPromises.push(
        Promise.all(promises).then(function compileSuccess(scripts) {
            var compiledModule = scripts.shift();
            var datamodelDecl = scripts.shift();

            return new CompiledInvokeConstructor(
                invokeConstructor.name,
                datamodelDecl,
                rootScripts,
                compiledModule
            );
        }, function compileError(err) {
          cb(err);
        })
      );
    }

    return Promise.all(invokeConstructorPromises).then(function(compiledInvokeConstructors){
        cb(null, new ModelFactoryFactory(compiledInvokeConstructors));
      },function compileError(err) {
        cb(err);
      });

}

function CompiledInvokeConstructor(name, datamodel, rootScripts, scxmlModule){
    this.name = name;
    this.datamodel = datamodel;
    this.rootScripts = rootScripts;
    this.module = scxmlModule;
}

/**
 * @constructor
 * @memberof scxml
 */
function ModelFactoryFactory(compiledInvokeConstructors) {
  this.compiledInvokeConstructors = compiledInvokeConstructors;
}

/**
 * This callback is displayed as a global member.
 * @callback prepareCallback
 * @param {Error} err
 * @param {scxml.ModelFactory} modelFactory This is the model factory that we can pass to the {@link scxml.scion.Statechart} constructor
 */

/**
 * Prepares an scxml model for execution by binding it to an execution context
 * @param  {prepareCallback} cb  Callback to execute with the prepared model or an error
 *   The prepared model is a function to be passed into a SCION StateChart object
 * @param  {vm.Context | object} [executionContext] The execution context  (e.g. v8 VM sandbox).
 *   If a vm.Context object is provided, then the compiled SCXML module code is evaluated in that context.
 *   Otherwise, if a regular object is provided, then the given object is "contextified", which means that it is passed to vm.createContext to create a new execution context. Object keys are exposed as global variables on the new context in which the generated SCXML module code is evaluated.
 * @param  {HostContext} [hostContext]  Context provided by the interpreter host
 */
ModelFactoryFactory.prototype.prepare = function(cb, executionContext, hostContext) {
    var modelFns = [];
    var promises =
      this.compiledInvokeConstructors.map( (compiledInvokeConstructor, i) => {
        let execContext;
        [execContext, hostContext] = util.initContexts(executionContext, hostContext);
        let scriptPromises = util.fetchScripts(compiledInvokeConstructor, hostContext);      //FIXME: check what this is doing

        return Promise.all(scriptPromises).then(function resolved(scripts) {
            try {
                if (compiledInvokeConstructor.datamodel) {
                    compiledInvokeConstructor.datamodel.runInContext(execContext);
                }

                for (let i = 0; i < compiledInvokeConstructor.rootScripts.length; i++) {
                    var scriptInfo = compiledInvokeConstructor.rootScripts[i];
                    if(scriptInfo.src){
                      //lazily compile scripts that have been downloaded lazily
                      var content = scriptInfo.$wrap ? scriptInfo.$wrap(scriptInfo.content) : scriptInfo.content;
                      scriptInfo.compiled = new vm.Script(content, {filename: scriptInfo.src});
                    }
                    assert(scriptInfo.compiled);
                    scriptInfo.compiled.runInContext(execContext);
                }

                if(this.compiledInvokeConstructors.length === (i + 1)){
                  for(let fn of modelFns){
                    execContext[fn.name] = fn; //this should allow each FnModel to reference every other by name
                  }
                }
                let modelFn = compiledInvokeConstructor.module.runInContext(execContext);   //each iteration, add invokers to the execution context, which is shared memory
                modelFns.push(modelFn);
                return modelFn;
            } catch (e) {
                cb(e);
            }
        }.bind(this), function rejected(err) {
            cb(err);
        });
    });

  Promise.all(promises).then(function(){
      cb(null, modelFns[modelFns.length - 1]);    //assume last modelFn will be the rootConstructor
  });
}

function createModule(url,scJson,hostContext,cb){
    if (platform.debug) {
        console.log('scjson',JSON.stringify(scJson, undefined, 2));
        if (!hostContext.hasOwnProperty('debug')) {
            hostContext.debug = true;
        }
    }

    scjsonToModule.startTraversal(url, scJson, hostContext).then(function resolved(rawModule) {
        if (platform.debug && rawModule.name) {
            fs.writeFileSync('/var/tmp/' + rawModule.name + '.scion', rawModule.module);
        }

        for (var i = 0; i < rawModule.invokeConstructors.length; i++) {
          let invokeConstructor = rawModule.invokeConstructors[i];
          for (var j = 0; j < invokeConstructor.rootScripts.length; j++) {
              var curScript = invokeConstructor.rootScripts[j];
              if (curScript.src) {
                curScript.src = platform.url.resolve(url, curScript.src);
              }
          }
        }

        module.exports.handleRawModule(url, rawModule, hostContext, cb);
    }, function rejected(err) {
        cb(err);
    });
}

module.exports = {
  documentStringToModel : documentStringToModel,
  handleRawModule : compileModule
};
<commit_msg>Fix bug in script-src in the browser.<commit_after>/*
     Copyright 2011-2012 Jacob Beard, INFICON, and other SCION contributors

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

             http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
*/

"use strict";

var compilerInternals = require('./compiler-internals'),
    platform = require('./platform-bootstrap/node/platform'),
    fs = require('fs'),
    vm = require('vm'),
    SourceNode = require('source-map').SourceNode,
    assert = require('assert'),
    util = require('../util');

var scxmlToScjson = compilerInternals.scxmlToScjson,
    scjsonToModule = compilerInternals.scjsonToModule,
    scJsonAnalyzer = compilerInternals.scJsonAnalyzer;

/**
 * Compile the raw scxml document into a compiled JS module
 * Top-level scripts are extracted so that they can be compiled and executed independently
 * @memberof scxml
 * @param  {string}   url       The url of the scxml document
 * @param  {string}   docString The raw scxml document to be parsed
 * @param  {modelCallback} cb        The callback to invoke once the document has been parsed
 * @param  {HostContext}   [hostContext]   Context provided by the interpreter host
 */
function documentStringToModel(url,docString,cb,hostContext){
    if (typeof hostContext !== 'object' || hostContext === null) {
        hostContext = {};
    }

    var scJson = scxmlToScjson(docString);

    scJsonAnalyzer.analyze(scJson, url, hostContext, function (result) {
        if (result.errors.length) {
            cb(result.errors);
            return;
        };

        createModule(url, result.scJson, hostContext, cb);
    });
}

/**
 * Compile the generated scxml module and any embedded or external scripts
 * @param  {string}   docUrl        The scxml document url
 * @param  {SCJsonRawModule}   rawModule      The raw SCION module created by scjson-to-module
 * @param  {HostContext}   [hostContext]   Context provided by the interpreter host
 * @param  {function} cb            Callback to invoke with the compiled module or an error
 * @private
 */
function compileModule(docUrl, rawModule, hostContext, cb) {
    const promiseOffset = 2;
    let invokeConstructorPromises = [];
    //TODO: modules need to be evaluated in order of dependencies. we need to test recursive invoke content.
    for(let invokeConstructor of rawModule.invokeConstructors.reverse()){

      let rootScripts = invokeConstructor.rootScripts;
      let scriptCount = rootScripts.length;
      let promises = new Array(scriptCount + promiseOffset);

      for (var i = 0; i < scriptCount; i++) {
          var curScript = rootScripts[i];
          if (curScript.src) {
              // defer the fetch until ModelFactoryFactory.prepare
              promises[i+promiseOffset] = Promise.resolve(curScript);
          } else {
              promises[i+promiseOffset] = new Promise(function(resolve, reject) {
                  try {
                      var content = curScript.content;
                      delete curScript.content;
                      var compiledScript = platform.module.compileScript(content, {
                          filename: docUrl,
                          lineOffset: curScript.$line,
                          columnOffset: curScript.$column
                      });
                      curScript.compiled = compiledScript;
                      resolve(curScript);
                  } catch(e) {
                      reject(e);
                  }
              });
          }
      }

      promises[0] = new Promise(function(resolve, reject) {
          try {
              var compiledModule = platform.module.compileScript('(' + invokeConstructor.module + ')', {
                  filename: docUrl
              });

              resolve(compiledModule);
          } catch(e) {
              reject(e);
          }
      });

      promises[1] = new Promise(function(resolve, reject) {
          if (!invokeConstructor.datamodel) {
              resolve(undefined);
          } else {
              try {
                  var compiledDatamodel = platform.module.compileScript(invokeConstructor.datamodel, {
                      filename: docUrl
                  });

                  resolve(compiledDatamodel);
              } catch(e) {
                  reject(e);
              }
          }
      })

      invokeConstructorPromises.push(
        Promise.all(promises).then(function compileSuccess(scripts) {
            var compiledModule = scripts.shift();
            var datamodelDecl = scripts.shift();

            return new CompiledInvokeConstructor(
                invokeConstructor.name,
                datamodelDecl,
                rootScripts,
                compiledModule
            );
        }, function compileError(err) {
          cb(err);
        })
      );
    }

    return Promise.all(invokeConstructorPromises).then(function(compiledInvokeConstructors){
        cb(null, new ModelFactoryFactory(compiledInvokeConstructors));
      },function compileError(err) {
        cb(err);
      });

}

function CompiledInvokeConstructor(name, datamodel, rootScripts, scxmlModule){
    this.name = name;
    this.datamodel = datamodel;
    this.rootScripts = rootScripts;
    this.module = scxmlModule;
}

/**
 * @constructor
 * @memberof scxml
 */
function ModelFactoryFactory(compiledInvokeConstructors) {
  this.compiledInvokeConstructors = compiledInvokeConstructors;
}

/**
 * This callback is displayed as a global member.
 * @callback prepareCallback
 * @param {Error} err
 * @param {scxml.ModelFactory} modelFactory This is the model factory that we can pass to the {@link scxml.scion.Statechart} constructor
 */

/**
 * Prepares an scxml model for execution by binding it to an execution context
 * @param  {prepareCallback} cb  Callback to execute with the prepared model or an error
 *   The prepared model is a function to be passed into a SCION StateChart object
 * @param  {vm.Context | object} [executionContext] The execution context  (e.g. v8 VM sandbox).
 *   If a vm.Context object is provided, then the compiled SCXML module code is evaluated in that context.
 *   Otherwise, if a regular object is provided, then the given object is "contextified", which means that it is passed to vm.createContext to create a new execution context. Object keys are exposed as global variables on the new context in which the generated SCXML module code is evaluated.
 * @param  {HostContext} [hostContext]  Context provided by the interpreter host
 */
ModelFactoryFactory.prototype.prepare = function(cb, executionContext, hostContext) {
    var modelFns = [];
    var promises =
      this.compiledInvokeConstructors.map( (compiledInvokeConstructor, i) => {
        let execContext;
        [execContext, hostContext] = util.initContexts(executionContext, hostContext);
        let scriptPromises = util.fetchScripts(compiledInvokeConstructor, hostContext);      //FIXME: check what this is doing

        return Promise.all(scriptPromises).then(function resolved(scripts) {
            try {
                if (compiledInvokeConstructor.datamodel) {
                    compiledInvokeConstructor.datamodel.runInContext(execContext);
                }

                for (let i = 0; i < compiledInvokeConstructor.rootScripts.length; i++) {
                    var scriptInfo = compiledInvokeConstructor.rootScripts[i];
                    if(scriptInfo.src){
                      //lazily compile scripts that have been downloaded lazily
                      var content = scriptInfo.$wrap ? scriptInfo.$wrap(scriptInfo.content) : scriptInfo.content;
                      scriptInfo.compiled = new vm.Script(content.toString(), {filename: scriptInfo.src});
                    }
                    assert(scriptInfo.compiled);
                    scriptInfo.compiled.runInContext(execContext);
                }

                if(this.compiledInvokeConstructors.length === (i + 1)){
                  for(let fn of modelFns){
                    execContext[fn.name] = fn; //this should allow each FnModel to reference every other by name
                  }
                }
                let modelFn = compiledInvokeConstructor.module.runInContext(execContext);   //each iteration, add invokers to the execution context, which is shared memory
                modelFns.push(modelFn);
                return modelFn;
            } catch (e) {
                cb(e);
            }
        }.bind(this), function rejected(err) {
            cb(err);
        });
    });

  Promise.all(promises).then(function(){
      cb(null, modelFns[modelFns.length - 1]);    //assume last modelFn will be the rootConstructor
  });
}

function createModule(url,scJson,hostContext,cb){
    if (platform.debug) {
        console.log('scjson',JSON.stringify(scJson, undefined, 2));
        if (!hostContext.hasOwnProperty('debug')) {
            hostContext.debug = true;
        }
    }

    scjsonToModule.startTraversal(url, scJson, hostContext).then(function resolved(rawModule) {
        if (platform.debug && rawModule.name) {
            fs.writeFileSync('/var/tmp/' + rawModule.name + '.scion', rawModule.module);
        }

        for (var i = 0; i < rawModule.invokeConstructors.length; i++) {
          let invokeConstructor = rawModule.invokeConstructors[i];
          for (var j = 0; j < invokeConstructor.rootScripts.length; j++) {
              var curScript = invokeConstructor.rootScripts[j];
              if (curScript.src) {
                curScript.src = platform.url.resolve(url, curScript.src);
              }
          }
        }

        module.exports.handleRawModule(url, rawModule, hostContext, cb);
    }, function rejected(err) {
        cb(err);
    });
}

module.exports = {
  documentStringToModel : documentStringToModel,
  handleRawModule : compileModule
};
<|endoftext|>


<commit_before>angular.module('myApp.users', ['ngRoute', 'ui.gravatar'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/users', {
      templateUrl: 'users/users.html',
      controller: 'UsersController'
  });
}])

.controller('UsersController', ['$http', '$scope', '$location', 'CONFIG', '$q',
            function($http, $scope, $location, CONFIG, $q) {

  $scope.users = [];

  $http.get(CONFIG.API_URL + '/users')
  .then(function(response) {
    $scope.users = response.data.Users;
    for (var i = 0; i < $scope.users.length; i++) {
      var user = $scope.users[i];

      if (user.user_email === localStorage.user_email) {
          $scope.users.splice(i, 1);
          break;
      }
    }
  })
  .then(function() {
    var requests = [];

    for (var i = 0; i < $scope.users.length; i++) {
      requests.push($http.get(CONFIG.API_URL + '/users/' + $scope.users[i].user_id + '/answers'));
    }

    return $q.all(requests)
      .then(function(responses) {
        for (var i = 0; i < responses.length; i++) {
          var response = responses[i];
          if (response.data.Answers && response.data.Answers.length) {
            $scope.users[i].total = response.data.Answers.length;
            return $http.get(CONFIG.API_URL + 'users/' + localStorage.user_id + '/score/' + $scope.users[i].user_id)
            .then(function(response) {
              $scope.users[i].score = response.data.Score[0].score;
            });
          }
        }
      });
  });

  $scope.openChallenge = function(user) {
    localStorage.challenged_user_id = user.user_id;
    $location.url("/challenge");
  }

}]);

<commit_msg>Fixing scoring<commit_after>angular.module('myApp.users', ['ngRoute', 'ui.gravatar'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/users', {
      templateUrl: 'users/users.html',
      controller: 'UsersController'
  });
}])

.controller('UsersController', ['$http', '$scope', '$location', 'CONFIG', '$q',
            function($http, $scope, $location, CONFIG, $q) {

  $scope.users = [];

  $http.get(CONFIG.API_URL + '/users')
  .then(function(response) {
    $scope.users = response.data.Users;
    for (var i = 0; i < $scope.users.length; i++) {
      var user = $scope.users[i];

      if (user.user_email === localStorage.user_email) {
          $scope.users.splice(i, 1);
          break;
      }
    }
  })
  .then(function() {
    var requests = [];

    for (var i = 0; i < $scope.users.length; i++) {
      requests.push($http.get(CONFIG.API_URL + '/users/' + $scope.users[i].user_id + '/answers'));
    }

    return $q.all(requests)
      .then(function(responses) {
        var reqs = [], response;
        for (var i = 0; i < responses.length; i++) {
          response = responses[i]
          if (response.data.Answers && response.data.Answers.length) {
            $scope.users[i].total = response.data.Answers.length;
            reqs.push($http.get(CONFIG.API_URL + 'users/' + localStorage.user_id + '/score/' + $scope.users[i].user_id));
          }
        }

        $q.all(reqs).then(function(responses) {
          for(var i = 0; i<responses.length; i++) {
            $scope.users[i].score = responses[i].data.Score[0].score;
          }
        });
      });
  });

  $scope.openChallenge = function(user) {
    localStorage.challenged_user_id = user.user_id;
    $location.url("/challenge");
  }

}]);

<|endoftext|>


<commit_before>'use strict';

angular.module('Frontend.Venta', ['ngRoute','angular-jwt','angular-storage'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/venta', {
    templateUrl: 'venta/venta.html',
    controller: 'VentaController'
  });
}])

.controller('VentaController', function($scope, store, jwtHelper, $http, backendAPIservice, $location, $window) {
    $scope.terminado=false;
    $scope.contado=true;
    $scope.cliente=1;
    $scope.base21=0.00;
    $scope.iva21=0.00;
    $scope.base10=0.00;
    $scope.iva10=0.00;
    $scope.base4=0.00;
    $scope.iva4=0.00;
    $scope.total=0.00;
    $scope.articulopr;
    $scope.respuesta;
    $scope.error;
    $scope.codigo;
    $scope.cero=0;
    $scope.prueba;
    $scope.activo;
    $scope.numventa;

    $scope.listaVenta = [];
    $scope.listaProducto = [];
    $scope.listaSocio = [];
    $scope.listaTipo = [];

    if(store.get('token')){
      var token = store.get('token');
      if(!jwtHelper.isTokenExpired(token))
      {
        backendAPIservice.getProductos().success(function (recibe) {
          var productosArray = recibe.response.productos;
          console.log(JSON.stringify(productosArray));
          $scope.listaProducto = productosArray;
          store.set('token',recibe.response.token);

        });

        backendAPIservice.getClientes().success(function (recibe) {
          var sociosArray = recibe.response.socios;
          console.log(JSON.stringify(sociosArray));
          $scope.listaSocio = sociosArray;
          store.set('token',recibe.response.token);
        });

        backendAPIservice.getTipos().success(function (recibe) {
          var tiposArray = recibe.response.tipos;
          console.log(JSON.stringify(tiposArray));
          $scope.listaTipo = tiposArray;
          store.set('token',recibe.response.token);
        });
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    }
    else
    {
      store.remove('token');
      store.set('nombre', "Sin conexion");
      $location.path("/login");
    }

    $scope.Aniadir=function(pid, pnombre, pprecio, piva)
    {
      var elemento;
      var anadido=false;
      for(elemento in $scope.listaVenta) {
        if($scope.listaVenta[elemento].id == pid) {
          $scope.listaVenta[elemento].cantidad = $scope.listaVenta[elemento].cantidad+1;
          anadido=true;
        }
      }
      if(anadido==false)
      {
        $scope.listaVenta.push({id:pid, nombre:pnombre, precio:pprecio, iva:piva, cantidad:1 });
      }
      $scope.Totales();
    };

    $scope.clienteElegido=function(value) {
      if($scope.cliente==1){ $scope.contado=true; }
      if (value.id==$scope.cliente){
        return true;
      } else {
        return false;
      }
    };

    $scope.Borrar=function(index) {
      $scope.listaVenta.splice(index, 1);
      $scope.Totales();
    };

    $scope.Totales=function() {
      var elemento;
      $scope.base21=0.00;
      $scope.iva21=0.00;
      $scope.base10=0.00;
      $scope.iva10=0.00;
      $scope.base4=0.00;
      $scope.iva4=0.00;
      for(elemento in $scope.listaVenta) {
        if($scope.listaVenta[elemento].iva=="21") {
         $scope.base21 += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva21 = ($scope.base21 * 21.00 )/100.00;
        };
        if($scope.listaVenta[elemento].iva==10) {
         $scope.base10  += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva10 = ($scope.base10 * 10.00 )/100.00;
        };
        if($scope.listaVenta[elemento].iva==4) {
         $scope.base4  += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva4 = ($scope.base4 * 4.00 )/100.00;
        };
      }
      $scope.total = $scope.base21 + $scope.iva21 + $scope.base10 + $scope.iva10 + $scope.base4 + $scope.iva4;
    };

    $scope.Finalizar=function() {
      backendAPIservice.postVenta($scope.cliente, $scope.contado, $scope.listaVenta).success(function(recibe){
        var respuesta1 = recibe.response.respuesta;
        var numventa = recibe.response.venta;
        console.log(JSON.stringify(respuesta1));
        console.log(JSON.stringify(numventa));
        $scope.respuesta = respuesta1;
        $scope.numventa = numventa;
        if(recibe.code==0) store.set('token',recibe.response.token);
        $scope.terminado=true;
      });
    };

    $scope.Continuar=function() {
      /*html2canvas(document.getElementById('imprimeesto'), {
        onrendered: function (canvas) {
          var data = canvas.toDataURL();
          var docDefinition = {
            content: [{
              image: data,
              width: 500,
            }]
          };
          pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
        }
      })*/
      $scope.terminado=false;
      $scope.contado=true;
      $scope.cliente=1;
      $scope.base21=0.00;
      $scope.iva21=0.00;
      $scope.base10=0.00;
      $scope.iva10=0.00;
      $scope.base4=0.00;
      $scope.iva4=0.00;
      $scope.total=0.00;
      $scope.articulopr;
      $scope.respuesta;
      $scope.error;
      $scope.codigo;
      $scope.cero=0;
      $scope.prueba;
      $scope.activo;

      $scope.listaVenta = [];
      $scope.listaProducto = [];
      $scope.listaSocio = [];
      $scope.listaTipo = [];

      if(store.get('token')){
        var token = store.get('token');
        if(!jwtHelper.isTokenExpired(token))
        {
          backendAPIservice.getProductos().success(function (recibe) {
            var productosArray = recibe.response.productos;
            console.log(JSON.stringify(productosArray));
            $scope.listaProducto = productosArray;
            store.set('token',recibe.response.token);

          });

          backendAPIservice.getClientes().success(function (recibe) {
            var sociosArray = recibe.response.socios;
            console.log(JSON.stringify(sociosArray));
            $scope.listaSocio = sociosArray;
            store.set('token',recibe.response.token);
          });

          backendAPIservice.getTipos().success(function (recibe) {
            var tiposArray = recibe.response.tipos;
            console.log(JSON.stringify(tiposArray));
            $scope.listaTipo = tiposArray;
            store.set('token',recibe.response.token);
          });
        }
        else
        {
          store.remove('token');
          store.set('nombre', "Sin conexion");
          $location.path("/login");
        }
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    };

    /*$scope.printDiv=function(divName){
      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;
      document.body.innerHTML = printContents;
      window.print();
      document.body.innerHTML = originalContents;
    };*/

    $scope.printDiv = function(divName) {
      var printContents = document.getElementById(divName).innerHTML;
      var popupWin = window.open('', '_blank', 'width=300,height=300');
      popupWin.document.open();
      popupWin.document.write('<link rel="stylesheet" type="text/css" href="app.css" />' + printContents + '');
      popupWin.document.close();
    };

    /*$scope.printDiv = function (divName) {

      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;

      if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
          var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
          popupWin.window.focus();
          popupWin.document.write('<!DOCTYPE html>' +
              '<link rel="stylesheet" type="text/css" href="app.css" />' +
              '
' + printContents + '
');
          popupWin.onbeforeunload = function (event) {
              popupWin.close();
              return '.\n';
          };
          popupWin.onabort = function (event) {
              popupWin.document.close();
              popupWin.close();
          }
      } else {
          var popupWin = window.open('', '_blank', 'width=800,height=600');
          popupWin.document.open();
          popupWin.document.write('<link rel="stylesheet" type="text/css" href="app.css" />' + printContents + '');
          popupWin.document.close();
      }
      popupWin.document.close();

      return true;
    };*/

});
<commit_msg>20160905-1745<commit_after>'use strict';

angular.module('Frontend.Venta', ['ngRoute','angular-jwt','angular-storage'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/venta', {
    templateUrl: 'venta/venta.html',
    controller: 'VentaController'
  });
}])

.controller('VentaController', function($scope, store, jwtHelper, $http, backendAPIservice, $location, $window) {
    $scope.terminado=false;
    $scope.contado=true;
    $scope.cliente=1;
    $scope.base21=0.00;
    $scope.iva21=0.00;
    $scope.base10=0.00;
    $scope.iva10=0.00;
    $scope.base4=0.00;
    $scope.iva4=0.00;
    $scope.total=0.00;
    $scope.articulopr;
    $scope.respuesta;
    $scope.error;
    $scope.codigo;
    $scope.cero=0;
    $scope.prueba;
    $scope.activo;
    $scope.numventa;

    $scope.listaVenta = [];
    $scope.listaProducto = [];
    $scope.listaSocio = [];
    $scope.listaTipo = [];

    if(store.get('token')){
      var token = store.get('token');
      if(!jwtHelper.isTokenExpired(token))
      {
        backendAPIservice.getProductos().success(function (recibe) {
          var productosArray = recibe.response.productos;
          console.log(JSON.stringify(productosArray));
          $scope.listaProducto = productosArray;
          store.set('token',recibe.response.token);

        });

        backendAPIservice.getClientes().success(function (recibe) {
          var sociosArray = recibe.response.socios;
          console.log(JSON.stringify(sociosArray));
          $scope.listaSocio = sociosArray;
          store.set('token',recibe.response.token);
        });

        backendAPIservice.getTipos().success(function (recibe) {
          var tiposArray = recibe.response.tipos;
          console.log(JSON.stringify(tiposArray));
          $scope.listaTipo = tiposArray;
          store.set('token',recibe.response.token);
        });
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    }
    else
    {
      store.remove('token');
      store.set('nombre', "Sin conexion");
      $location.path("/login");
    }

    $scope.Aniadir=function(pid, pnombre, pprecio, piva)
    {
      var elemento;
      var anadido=false;
      for(elemento in $scope.listaVenta) {
        if($scope.listaVenta[elemento].id == pid) {
          $scope.listaVenta[elemento].cantidad = $scope.listaVenta[elemento].cantidad+1;
          anadido=true;
        }
      }
      if(anadido==false)
      {
        $scope.listaVenta.push({id:pid, nombre:pnombre, precio:pprecio, iva:piva, cantidad:1 });
      }
      $scope.Totales();
    };

    $scope.clienteElegido=function(value) {
      if($scope.cliente==1){ $scope.contado=true; }
      if (value.id==$scope.cliente){
        return true;
      } else {
        return false;
      }
    };

    $scope.Borrar=function(index) {
      $scope.listaVenta.splice(index, 1);
      $scope.Totales();
    };

    $scope.Totales=function() {
      var elemento;
      $scope.base21=0.00;
      $scope.iva21=0.00;
      $scope.base10=0.00;
      $scope.iva10=0.00;
      $scope.base4=0.00;
      $scope.iva4=0.00;
      for(elemento in $scope.listaVenta) {
        if($scope.listaVenta[elemento].iva=="21") {
         $scope.base21 += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva21 = ($scope.base21 * 21.00 )/100.00;
        };
        if($scope.listaVenta[elemento].iva==10) {
         $scope.base10  += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva10 = ($scope.base10 * 10.00 )/100.00;
        };
        if($scope.listaVenta[elemento].iva==4) {
         $scope.base4  += ($scope.listaVenta[elemento].precio * $scope.listaVenta[elemento].cantidad);
         $scope.iva4 = ($scope.base4 * 4.00 )/100.00;
        };
      }
      $scope.total = $scope.base21 + $scope.iva21 + $scope.base10 + $scope.iva10 + $scope.base4 + $scope.iva4;
    };

    $scope.Finalizar=function() {
      backendAPIservice.postVenta($scope.cliente, $scope.contado, $scope.listaVenta).success(function(recibe){
        var respuesta1 = recibe.response.respuesta;
        var numventa = recibe.response.venta;
        console.log(JSON.stringify(respuesta1));
        console.log(JSON.stringify(numventa));
        $scope.respuesta = respuesta1;
        $scope.numventa = numventa;
        if(recibe.code==0) store.set('token',recibe.response.token);
        $scope.terminado=true;
      });
    };

    $scope.Continuar=function() {
      /*html2canvas(document.getElementById('imprimeesto'), {
        onrendered: function (canvas) {
          var data = canvas.toDataURL();
          var docDefinition = {
            content: [{
              image: data,
              width: 500,
            }]
          };
          pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
        }
      })*/
      $scope.terminado=false;
      $scope.contado=true;
      $scope.cerrado=false;
      $scope.cliente=1;
      $scope.base21=0.00;
      $scope.iva21=0.00;
      $scope.base10=0.00;
      $scope.iva10=0.00;
      $scope.base4=0.00;
      $scope.iva4=0.00;
      $scope.total=0.00;
      $scope.articulopr;
      $scope.respuesta;
      $scope.error;
      $scope.codigo;
      $scope.cero=0;
      $scope.prueba;
      $scope.activo;

      $scope.listaVenta = [];
      $scope.listaProducto = [];
      $scope.listaSocio = [];
      $scope.listaTipo = [];

      if(store.get('token')){
        var token = store.get('token');
        if(!jwtHelper.isTokenExpired(token))
        {
          backendAPIservice.getProductos().success(function (recibe) {
            var productosArray = recibe.response.productos;
            var codigo = recibe.code;
            if(codigo!=0 $scope.cerrado=true);
            console.log(JSON.stringify(productosArray));
            $scope.listaProducto = productosArray;
            store.set('token',recibe.response.token);

          });

          backendAPIservice.getClientes().success(function (recibe) {
            var sociosArray = recibe.response.socios;
            console.log(JSON.stringify(sociosArray));
            $scope.listaSocio = sociosArray;
            store.set('token',recibe.response.token);
          });

          backendAPIservice.getTipos().success(function (recibe) {
            var tiposArray = recibe.response.tipos;
            console.log(JSON.stringify(tiposArray));
            $scope.listaTipo = tiposArray;
            store.set('token',recibe.response.token);
          });
        }
        else
        {
          store.remove('token');
          store.set('nombre', "Sin conexion");
          $location.path("/login");
        }
      }
      else
      {
        store.remove('token');
        store.set('nombre', "Sin conexion");
        $location.path("/login");
      }
    };

    /*$scope.printDiv=function(divName){
      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;
      document.body.innerHTML = printContents;
      window.print();
      document.body.innerHTML = originalContents;
    };*/

    $scope.printDiv = function(divName) {
      var printContents = document.getElementById(divName).innerHTML;
      var popupWin = window.open('', '_blank', 'width=300,height=300');
      popupWin.document.open();
      popupWin.document.write('<link rel="stylesheet" type="text/css" href="app.css" />' + printContents + '');
      popupWin.document.close();
    };

    /*$scope.printDiv = function (divName) {

      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;

      if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
          var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
          popupWin.window.focus();
          popupWin.document.write('<!DOCTYPE html>' +
              '<link rel="stylesheet" type="text/css" href="app.css" />' +
              '
' + printContents + '
');
          popupWin.onbeforeunload = function (event) {
              popupWin.close();
              return '.\n';
          };
          popupWin.onabort = function (event) {
              popupWin.document.close();
              popupWin.close();
          }
      } else {
          var popupWin = window.open('', '_blank', 'width=800,height=600');
          popupWin.document.open();
          popupWin.document.write('<link rel="stylesheet" type="text/css" href="app.css" />' + printContents + '');
          popupWin.document.close();
      }
      popupWin.document.close();

      return true;
    };*/

});
<|endoftext|>


<commit_before>import React from 'react/addons';
import Router from 'react-router';
import shell from 'shell';
import ContentRepositoryActions from '../actions/ContentRepositoryActions';

var ContentRepositoryCard = React.createClass({
  handlePreview: function () {
    shell.openExternal(this.props.repository.publicURL());
  },

  handleSubmit: function () {
    ContentRepositoryActions.prepareContent(this.props.repository);
    ContentRepositoryActions.prepareControl(this.props.repository);
  },

  handleRemove: function () {
    ContentRepositoryActions.remove(this.props.repository);
  },

  handleRetry: function () {
    ContentRepositoryActions.relaunch(this.props.repository);
  },

  render: function () {
    let repo = this.props.repository;
    let nameElement, detailElement, retryElement, submitElement;

    if (repo.canPreview()) {
      // Render the name as a link.
      nameElement = (
        {repo.name()}
      );
    } else {
      // Use a span instead.
      nameElement = (
        {repo.name()}
      );
    }

    if (repo.canSubmit()) {
      submitElement = (
        submit
      );
    } else {
      submitElement = (
        submit
      );
    }

    if (repo.error) {
      detailElement = (

{repo.error.toString()}

      );

      retryElement = (

retry

      )
    }

    return (

          {nameElement}
          {repo.state}

            {retryElement}

{submitElement}

<Router.Link to="editRepository" params={{id: repo.id}} className="btn btn-link">edit</Router.Link>

remove

        {detailElement}

    )
  }
})

module.exports = ContentRepositoryCard;
<commit_msg>Require confirmation before deleting repositories.<commit_after>import React from 'react/addons';
import Router from 'react-router';
import shell from 'shell';
import ContentRepositoryActions from '../actions/ContentRepositoryActions';

var ContentRepositoryCard = React.createClass({
  getInitialState: function () {
    return {
      isRemoving: false
    };
  },

  handlePreview: function () {
    shell.openExternal(this.props.repository.publicURL());
  },

  handleSubmit: function () {
    ContentRepositoryActions.prepareContent(this.props.repository);
    ContentRepositoryActions.prepareControl(this.props.repository);
  },

  handleMaybeRemove: function () {
    this.setState({isRemoving: true});
  },

  handleRemove: function () {
    ContentRepositoryActions.remove(this.props.repository);
  },

  handleNevermind: function() {
    this.setState({isRemoving: false});
  },

  handleRetry: function () {
    ContentRepositoryActions.relaunch(this.props.repository);
  },

  render: function () {
    if (!this.state.isRemoving) {
      return this.renderActive();
    } else {
      return this.renderRemovalConfirmation();
    }
  },

  renderActive: function () {
    let repo = this.props.repository;
    let nameElement, detailElement, retryElement, submitElement;

    if (repo.canPreview()) {
      // Render the name as a link.
      nameElement = (
        {repo.name()}
      );
    } else {
      // Use a span instead.
      nameElement = (
        {repo.name()}
      );
    }

    if (repo.canSubmit()) {
      submitElement = (
        submit
      );
    } else {
      submitElement = (
        submit
      );
    }

    if (repo.error) {
      detailElement = (

{repo.error.toString()}

      );

      retryElement = (

retry

      )
    }

    return (

          {nameElement}
          {repo.state}

            {retryElement}

{submitElement}

<Router.Link to="editRepository" params={{id: repo.id}} className="btn btn-link">edit</Router.Link>

remove

        {detailElement}

    );
  },

  renderRemovalConfirmation: function () {
    let repo = this.props.repository;

    return (

          Really delete {repo.name()}?

yes, really

what, no

    );
  }

})

module.exports = ContentRepositoryCard;
<|endoftext|>