<commit_before>import $ from "jquery";
import _ from "lodash";
import Promise from "bluebird";
import "../../lib/jquery.selection";
import "../../lib/jquery.esarea";
import Ui from "./ui";

let ui = new Ui();
window.ui = ui; // for debug

// TODO できればグローバルで定義しないほうがよさそう
let storedPost = {title: "", body: "", cursorPosition: 0, saved: false};

const loadPost = function() {
  let defaultPost = {title: "", body: "", cursorPosition: 0, saved: false};
  chrome.storage.sync.get(defaultPost, function(post) {
    storedPost = post;

    ui.toggle("save-button", "disabled", post.saved);

    ui.title(post.title);
    ui.body(post.body);
    if (ui.title() != "") {
      // Move cursor at previous position
      ui.moveFocus('body', post.cursorPosition);
    }
  });
}

const getConfig = function() {
  return new Promise(function(resolve, reject) {
    let defaultConfig = {teamName: "", token: "", teamIcon: "", postId: ""};
    chrome.storage.sync.get(defaultConfig, function(config) {
      if (!config.teamName || !config.token) {
        ui.toggle("option-link", "show", true);
        ui.teamName("Configuration failed");

        reject("Please configure options (\\( ˘⊖˘)/)");
      } else {
        ui.toggle("option-link", "show", false);

        if (config.postId != "") {
          let link = `https://${config.teamName}.esa.io/posts/${config.postId}`;
          ui.savedPostLink(link);
        }

        ui.teamName(config.teamName);

        resolve(config);
      }
    });
  });
}

const searchPost = function(config) {
  return new Promise(function(resolve, reject) {
    let title = ui.title();
    let category = "";

    if (hasCategory(title)) {
      category = /(.+)\/.+/.exec(title)[1];
      title = /.+\/(.+)/.exec(title)[1];
    }

    let q = `name:${title}`;
    if (category.length != 0) { q = `${q} category:${category}` }

    $.ajax({
      type: "GET",
      url: `https://api.esa.io/v1/teams/${config.teamName}/posts`,
      data: {
        q: q,
        access_token: config.token
      }
    }).then(
      function(response) {
        let hitPost;
        // カテゴリ無しだけを検索する方法がわからなかったので別途絞込している
        if (category.length == 0) {
          hitPost = _.find(response.posts, { name: title, category: null });
        } else {
          // 1つしかない想定
          hitPost = response.posts[0];
        }

        // 記事があった場合は更新するためIDを保存する
        if (hitPost) {
          config.postId = hitPost.number;
        } else {
          config.postId = undefined;
        }
        chrome.storage.sync.set(config, function(){
          resolve(config);
        });
      },
      reject
    );
  })
}

const savePost = function(config) {
  return new Promise(function(resolve, reject) {
    let type;
    let url = `https://api.esa.io/v1/teams/${config.teamName}/posts`;
    let title = ui.title();
    let body = ui.body();

    let post = {name: title, category: "", body_md: body, message: "from tsuibami"};

    if (hasCategory(title)) {
      post["category"] = /(.+)\/.+/.exec(title)[1];
      post["name"] = /.+\/(.+)/.exec(title)[1];
    }

    let postId = config.postId;
    if (postId) {
      type = "PATCH";
      url = url + "/" + postId;
    } else {
      type = "POST";
    }

    $.ajax({
      type: type,
      url: url,
      data: {
        post: post,
        access_token: config.token
      }
    }).then(
      resolve,
      reject
    );
  });
}

const storePostAsSaved = function(response) {
  return new Promise(function(resolve, reject) {
    ui.toggle("save-button", "disabled", true);

    chrome.storage.sync.set({saved: true}, function(){
      storedPost.saved = true;
      resolve(response);
    });
  });
}

const clearPost = function(response) {
  if (!ui.checkedclear()) {
    return new Promise(function(resolve, reject) {
      ui.moveFocus("body");
      resolve(response);
    });
  }
  return new Promise(function(resolve, reject) {
    ui.title("");
    ui.body("");

    ui.toggle("save-button", "disabled", true);

    storedPost = {title: "", body: "", cursorPosition: 0, saved: true};
    chrome.storage.sync.set(storedPost, function() {
      if (chrome.runtime.lastError) {
        reject(response);
      } else {
        resolve(response);
      }
    });
  });
}

const notifySaved = function(response) {
  return new Promise(function(resolve, reject) {
    let newPostId = response.number;
    let message;

    chrome.storage.sync.set({postId: newPostId}, function(){
      ui.savedPostLink(response.url);
      // 最初の保存の時だけメッセージを変える
      if (response.revision_number == 1) {
        message = "created!";
      } else {
        message = "updated!";
      }
      resolve(message);
    });
  });
}

const hasCategory = function(title) {
  return /.+\/.+/.test(title);
}

const notifyReady = function(config) {
  $(".team__icon")[0].src = config.teamIcon;
}

const notifySuccess = function(msg) {
  showMessage(msg + " (\\( ⁰⊖⁰)/)", true);
}

const notifyError = function(msg) {
  console.log(msg);
  showMessage(msg);
}

const showMessage = function(message, succeeded) {
  $(".message").show();

  $(".message__body").text(message);
  $(".message__body").removeClass("message__body-color-success");
  $(".message__body").removeClass("message__body-color-failure");

  if (succeeded) {
    $(".message__body").addClass("message__body-color-success");
    setTimeout(function() {
      $(".message").fadeOut("normal", function() {
        $(".message__body").text("");
      });
    }, 2000);
  } else {
    $(".message__body").addClass("message__body-color-failure");
  }
}

const storeTitle = function() {
  let title = ui.title();

  if (title != storedPost.title) {
    storedPost.title = title;
    storedPost.saved = false;
    store({title: title, saved: false});
    ui.toggle("save-button", "disabled", false);
  }
}

const storeBody = function() {
  let body = ui.body();

  if (body != storedPost.body) {
    storedPost.body = body;
    storedPost.saved = false;
    ui.toggle("save-button", "disabled", false);
  }

  let cursorPosition = $(".post__body")[0].selectionStart;
  if (cursorPosition != storedPost.cursorPosition) {
    storedPost.currentPosition = cursorPosition;
  }
  store(storedPost);
}

const storeCursorPosition = function() {
  let cursorPosition = $(".post__body")[0].selectionStart;
  if (cursorPosition != storedPost.cursorPosition) {
    store({cursorPosition: cursorPosition});
  }
}

const store = function(data) {
  chrome.storage.sync.set(data, function(){
    if (chrome.runtime.lastError) {
      showMessage("Error: " + chrome.runtime.lastError.message, false);
    }
  });
}

const showSavedStatus = function(saving) {
  $(".esa__post-button").text(saving ? "Saving..." : "Save as WIP");
}

const runSaveProcess = function() {
  ui.toggle("save-button", "disabled", true);
  showSavedStatus(true);
  getConfig().then(searchPost).then(savePost).then(storePostAsSaved).then(clearPost).then(notifySaved).then(notifySuccess).catch(notifyError).finally(function() {
    showSavedStatus(false);
  });
}

const runSaveProcessByShortcut = function(event) {
  // Ctrl+s or Cmd+s
  if ((event.metaKey || event.ctrlKey) && event.keyCode == 83) {
    event.preventDefault();
    runSaveProcess();
  }
}

$(function() {
  loadPost();
  getConfig().then(notifyReady).catch(notifyError);

  $(".post__title").on("keyup", _.debounce(storeTitle, 200));
  $(".post__body").on("keyup", _.debounce(storeBody, 200));
  $(".post__body").on("mouseup", storeCursorPosition);

  $(".post__title").on("keydown", runSaveProcessByShortcut);
  $(".post__body").on("keydown", runSaveProcessByShortcut);

  $(".post__body").esarea();

  $(".esa__post-button").on("click", runSaveProcess);
});
<commit_msg>Integrate notifyReady() to getConfig()<commit_after>import $ from 'jquery';
import _ from 'lodash';
import Promise from 'bluebird';
import '../../lib/jquery.selection';
import '../../lib/jquery.esarea';
import Ui from './ui';

let ui = new Ui();
window.ui = ui; // for debug

// TODO できればグローバルで定義しないほうがよさそう
let storedPost = { title: '', body: '', cursorPosition: 0, saved: false };

const loadPost = function() {
  let defaultPost = { title: '', body: '', cursorPosition: 0, saved: false };
  chrome.storage.sync.get(defaultPost, function(post) {
    storedPost = post;

    ui.toggle('save-button', 'disabled', post.saved);

    ui.title(post.title);
    ui.body(post.body);
    if (ui.title() != '') {
      // Move cursor at previous position
      ui.moveFocus('body', post.cursorPosition);
    }
  });
};

const getConfig = function() {
  return new Promise(function(resolve, reject) {
    let defaultConfig = { teamName: '', token: '', teamIcon: '', postId: '' };
    chrome.storage.sync.get(defaultConfig, function(config) {
      if (!config.teamName || !config.token) {
        ui.toggle('option-link', 'show', true);
        ui.teamName('Configuration failed');

        reject('Please configure options (\\( ˘⊖˘)/)');
      } else {
        ui.toggle('option-link', 'show', false);

        if (config.postId != '') {
          let link = `https://${config.teamName}.esa.io/posts/${config.postId}`;
          ui.savedPostLink(link);
        }

        ui.teamName(config.teamName);
        $('.team__icon')[0].src = config.teamIcon;

        resolve(config);
      }
    });
  });
};

const searchPost = function(config) {
  return new Promise(function(resolve, reject) {
    let title = ui.title();
    let category = '';

    if (hasCategory(title)) {
      category = /(.+)\/.+/.exec(title)[1];
      title = /.+\/(.+)/.exec(title)[1];
    }

    let q = `name:${title}`;
    if (category.length != 0) {
      q = `${q} category:${category}`;
    }

    $.ajax({
      type: 'GET',
      url: `https://api.esa.io/v1/teams/${config.teamName}/posts`,
      data: {
        q: q,
        access_token: config.token,
      },
    }).then(function(response) {
      let hitPost;
      // カテゴリ無しだけを検索する方法がわからなかったので別途絞込している
      if (category.length == 0) {
        hitPost = _.find(response.posts, { name: title, category: null });
      } else {
        // 1つしかない想定
        hitPost = response.posts[0];
      }

      // 記事があった場合は更新するためIDを保存する
      if (hitPost) {
        config.postId = hitPost.number;
      } else {
        config.postId = undefined;
      }
      chrome.storage.sync.set(config, function() {
        resolve(config);
      });
    }, reject);
  });
};

const savePost = function(config) {
  return new Promise(function(resolve, reject) {
    let type;
    let url = `https://api.esa.io/v1/teams/${config.teamName}/posts`;
    let title = ui.title();
    let body = ui.body();

    let post = {
      name: title,
      category: '',
      body_md: body,
      message: 'from tsuibami',
    };

    if (hasCategory(title)) {
      post['category'] = /(.+)\/.+/.exec(title)[1];
      post['name'] = /.+\/(.+)/.exec(title)[1];
    }

    let postId = config.postId;
    if (postId) {
      type = 'PATCH';
      url = url + '/' + postId;
    } else {
      type = 'POST';
    }

    $.ajax({
      type: type,
      url: url,
      data: {
        post: post,
        access_token: config.token,
      },
    }).then(resolve, reject);
  });
};

const storePostAsSaved = function(response) {
  return new Promise(function(resolve, reject) {
    ui.toggle('save-button', 'disabled', true);

    chrome.storage.sync.set({ saved: true }, function() {
      storedPost.saved = true;
      resolve(response);
    });
  });
};

const clearPost = function(response) {
  if (!ui.checkedclear()) {
    return new Promise(function(resolve, reject) {
      ui.moveFocus('body');
      resolve(response);
    });
  }
  return new Promise(function(resolve, reject) {
    ui.title('');
    ui.body('');

    ui.toggle('save-button', 'disabled', true);

    storedPost = { title: '', body: '', cursorPosition: 0, saved: true };
    chrome.storage.sync.set(storedPost, function() {
      if (chrome.runtime.lastError) {
        reject(response);
      } else {
        resolve(response);
      }
    });
  });
};

const notifySaved = function(response) {
  return new Promise(function(resolve, reject) {
    let newPostId = response.number;
    let message;

    chrome.storage.sync.set({ postId: newPostId }, function() {
      ui.savedPostLink(response.url);
      // 最初の保存の時だけメッセージを変える
      if (response.revision_number == 1) {
        message = 'created!';
      } else {
        message = 'updated!';
      }
      resolve(message);
    });
  });
};

const hasCategory = function(title) {
  return /.+\/.+/.test(title);
};

const notifySuccess = function(msg) {
  showMessage(msg + ' (\\( ⁰⊖⁰)/)', true);
};

const notifyError = function(msg) {
  console.log(msg);
  showMessage(msg);
};

const showMessage = function(message, succeeded) {
  $('.message').show();

  $('.message__body').text(message);
  $('.message__body').removeClass('message__body-color-success');
  $('.message__body').removeClass('message__body-color-failure');

  if (succeeded) {
    $('.message__body').addClass('message__body-color-success');
    setTimeout(function() {
      $('.message').fadeOut('normal', function() {
        $('.message__body').text('');
      });
    }, 2000);
  } else {
    $('.message__body').addClass('message__body-color-failure');
  }
};

const storeTitle = function() {
  let title = ui.title();

  if (title != storedPost.title) {
    storedPost.title = title;
    storedPost.saved = false;
    store({ title: title, saved: false });
    ui.toggle('save-button', 'disabled', false);
  }
};

const storeBody = function() {
  let body = ui.body();

  if (body != storedPost.body) {
    storedPost.body = body;
    storedPost.saved = false;
    ui.toggle('save-button', 'disabled', false);
  }

  let cursorPosition = $('.post__body')[0].selectionStart;
  if (cursorPosition != storedPost.cursorPosition) {
    storedPost.currentPosition = cursorPosition;
  }
  store(storedPost);
};

const storeCursorPosition = function() {
  let cursorPosition = $('.post__body')[0].selectionStart;
  if (cursorPosition != storedPost.cursorPosition) {
    store({ cursorPosition: cursorPosition });
  }
};

const store = function(data) {
  chrome.storage.sync.set(data, function() {
    if (chrome.runtime.lastError) {
      showMessage('Error: ' + chrome.runtime.lastError.message, false);
    }
  });
};

const showSavedStatus = function(saving) {
  $('.esa__post-button').text(saving ? 'Saving...' : 'Save as WIP');
};

const runSaveProcess = function() {
  ui.toggle('save-button', 'disabled', true);
  showSavedStatus(true);
  getConfig()
    .then(searchPost)
    .then(savePost)
    .then(storePostAsSaved)
    .then(clearPost)
    .then(notifySaved)
    .then(notifySuccess)
    .catch(notifyError)
    .finally(function() {
      showSavedStatus(false);
    });
};

const runSaveProcessByShortcut = function(event) {
  // Ctrl+s or Cmd+s
  if ((event.metaKey || event.ctrlKey) && event.keyCode == 83) {
    event.preventDefault();
    runSaveProcess();
  }
};

$(function() {
  loadPost();
  getConfig().catch(notifyError);

  $('.post__title').on('keyup', _.debounce(storeTitle, 200));
  $('.post__body').on('keyup', _.debounce(storeBody, 200));
  $('.post__body').on('mouseup', storeCursorPosition);

  $('.post__title').on('keydown', runSaveProcessByShortcut);
  $('.post__body').on('keydown', runSaveProcessByShortcut);

  $('.post__body').esarea();

  $('.esa__post-button').on('click', runSaveProcess);
});
<|endoftext|>


<commit_before>export { Button } from './components/button';
export { Grommet } from './components/grommet';
<commit_msg>reverted index change<commit_after>import { hpe, vanilla } from './themes';

export { Button } from './components/button';
export { Grommet } from './components/grommet';

export const theme = {
  vanilla, hpe,
};
<|endoftext|>


<commit_before>/**
 * @module Taxon
 * @author Erik Pearson
 * @version 0.1.0
 * @param {TaxonLibrary} taxon
 * @param {TriftLibrary} Thrift
 * @param {BluebirdPromise} Promise
 * @returns {Taxon_L12.factory}
 */
/*global define*/
/*jslint white: true, browser: true*/
define([
    'bluebird',
    './taxon/thrift_service',
    'kb/thrift/core',
    './common',
    // These don't have representations. Loading them causes the Thrift module
    // to be enhanced with additional properties (typically just a single
    //  property, the new capability added.)
    'kb/thrift/transport/xhr',
    'kb/thrift/protocol/binary'
], function (Promise, taxon, Thrift, common) {
    'use strict';

    /**
     * Represents an interface to the Taxon data service.
     * @alias module:Taxon
     * @constructs Taxon
     * @param {object} config
     * @param {ObjectReference} config.ref The object reference for the object to be accessed.
     * @param {string} config.url The url for the Taxon Service endpoint.
     * @param {string} config.token The KBase authorization token to be used to access the service.
     * @returns {Taxon} A taxon api object
     */
    function makeTaxonClient(config) {
        var objectReference,
            serviceUrl,
            authToken,
            timeout;

        common.validateCommonApiArgs(config);

        objectReference = config.ref;
        serviceUrl = config.url;
        authToken = config.token;
        timeout = config.timeout;

        /**
         * Creates and returns an instance of the Taxon Thrift client. Note that
         * this is
         *
         * @returns {Taxon_L22.taxon.thrift_serviceClient}
         * @private
         * @ignore
         */
        function client() {
            try {
                var transport = new Thrift.TXHRTransport(serviceUrl, {timeout: timeout}),
                    protocol = new Thrift.TBinaryProtocol(transport),
                    thriftClient = new taxon.thrift_serviceClient(protocol);
                return thriftClient;
            } catch (ex) {
                // Rethrow exceptions in our format:
                if (ex.type && ex.name) {
                    throw ex;
                }
                throw new TaxonException({
                    type: 'ThriftError',
                    message: 'An error was encountered creating the thrift client objects',
                    suggestion: 'This could be a configuration or runtime error. Please consult the console for the error object',
                    errorObject: ex
                });
            }
        }

        /**
         * If the Taxon has a parent object, this is returned. Otherwise,
         * it is ...
         *
         * @returns {Promise<ObjectReference|Error>} An object reference string
         * @throws {ThriftClientError} For networking and client side issues. These errors
         * are detected by the front end (javascript) code.
         * @throws {ThriftServiceError} For errors generated by the back end service.
         *
         */
        function getParent() {
            return client().get_parent(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         * Get a array of object reference strings which are children (sub objects)
         * of this Taxon.
         *
         * @returns {Array<ObjectReference>} An array of object references representing the children of this object.
         */
        function getChildren() {
            return client().get_children(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {Array<String>} An array of genome annotation strings
         */
        function getGenomeAnnotations() {
            return client().get_genome_annotations(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         * Get a list of taxonomic groups the species belongs to, with least specific first,
         * and most specific, that is the species itself, last.
         *
         * @returns {Array<String>} The lineage for this taxon, as an ordered list of taxonomic
         * ranks from least specific to most specific.
         *
         * @example
         *
         * Life
         *   Domain
         *     Kingdom
         *       Phylum
         *         Clas
         *           Order
         *             Family
         *               Genus
         *                 Species
         *
         */
        function getScientificLineage() {
            return client().get_scientific_lineage(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {String}
         */
        function getScientificName() {
            return Promise.try(function () {
                return client().get_scientific_name(authToken, objectReference, true)
                    .catch(taxon.AttributeException, function (err) {
                        return undefined;
                    });;
            });
        }

        /**
         *
         * @returns {Number}
         */
        function getTaxonomicId() {
            return client().get_taxonomic_id(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {String}
         */
        function getKingdom() {
            return client().get_kingdom(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {String}
         */
        function getDomain() {
            return client().get_domain(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         * The NCBI genetic code for the species.
         *
         * @returns {Number}
         * @see {@link http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi} NCBI "The Genetic Codes"
         */
        function getGeneticCode() {
            return client().get_genetic_code(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {Array<String>}
         */
        function getAliases() {
            return client().get_aliases(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        // API
        return Object.freeze({
            getParent: getParent,
            getChildren: getChildren,
            getGenomeAnnotations: getGenomeAnnotations,
            getScientificLineage: getScientificLineage,
            getScientificName: getScientificName,
            getTaxonomicId: getTaxonomicId,
            getKingdom: getKingdom,
            getDomain: getDomain,
            getGeneticCode: getGeneticCode,
            getAliases: getAliases
        });
    };

    return Object.freeze({
        make: function (config) {
            return makeTaxonClient(config);
        },
        makeClient: function (config) {
            return makeTaxonClient(config);
        },
        ClientException: common.ClientException,
        ServiceException: taxon.ServiceException,
        AuthorizationException: taxon.AuthorizationException,
        AuthenticationException: taxon.AuthenticationException,
        ObjectReferenceException: taxon.ObjectReferenceException,
        AttributeException: taxon.AttributeException,
        TypeException: taxon.TypeException
    });
});<commit_msg>change method names to match api (sans get_), forward all exceptions  from Thrift core.<commit_after>/**
 * @module Taxon
 * @author Erik Pearson
 * @version 0.1.0
 * @param {TaxonLibrary} taxon
 * @param {TriftLibrary} Thrift
 * @param {BluebirdPromise} Promise
 * @returns {Taxon_L12.factory}
 */
/*global define*/
/*jslint white: true, browser: true*/
define([
    'bluebird',
    './taxon/thrift_service',
    'kb/thrift/core',
    './common',
    // These don't have representations. Loading them causes the Thrift module
    // to be enhanced with additional properties (typically just a single
    //  property, the new capability added.)
    'kb/thrift/transport/xhr',
    'kb/thrift/protocol/binary'
], function (Promise, taxon, Thrift, common) {
    'use strict';

    /**
     * Represents an interface to the Taxon data service.
     * @alias module:Taxon
     * @constructs Taxon
     * @param {object} config
     * @param {ObjectReference} config.ref The object reference for the object to be accessed.
     * @param {string} config.url The url for the Taxon Service endpoint.
     * @param {string} config.token The KBase authorization token to be used to access the service.
     * @returns {Taxon} A taxon api object
     */
    function makeTaxonClient(config) {
        var objectReference,
            serviceUrl,
            authToken,
            timeout;

        common.validateCommonApiArgs(config);

        objectReference = config.ref;
        serviceUrl = config.url;
        authToken = config.token;
        timeout = config.timeout;

        /**
         * Creates and returns an instance of the Taxon Thrift client. Note that
         * this is
         *
         * @returns {Taxon_L22.taxon.thrift_serviceClient}
         * @private
         * @ignore
         */
        function client() {
            try {
                var transport = new Thrift.TXHRTransport(serviceUrl, {timeout: timeout}),
                    protocol = new Thrift.TBinaryProtocol(transport),
                    thriftClient = new taxon.thrift_serviceClient(protocol);
                return thriftClient;
            } catch (ex) {
                // Rethrow exceptions in our format:
                if (ex.type && ex.name) {
                    throw ex;
                }
                throw new TaxonException({
                    type: 'ThriftError',
                    message: 'An error was encountered creating the thrift client objects',
                    suggestion: 'This could be a configuration or runtime error. Please consult the console for the error object',
                    errorObject: ex
                });
            }
        }

        /**
         * If the Taxon has a parent object, this is returned. Otherwise,
         * it is ...
         *
         * @returns {Promise<ObjectReference|Error>} An object reference string
         * @throws {ThriftClientError} For networking and client side issues. These errors
         * are detected by the front end (javascript) code.
         * @throws {ThriftServiceError} For errors generated by the back end service.
         *
         */
        function parent() {
            return client().get_parent(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         * Get a array of object reference strings which are children (sub objects)
         * of this Taxon.
         *
         * @returns {Array<ObjectReference>} An array of object references representing the children of this object.
         */
        function children() {
            return client().get_children(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {Array<String>} An array of genome annotation strings
         */
        function genome_annotations() {
            return client().get_genome_annotations(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         * Get a list of taxonomic groups the species belongs to, with least specific first,
         * and most specific, that is the species itself, last.
         *
         * @returns {Array<String>} The lineage for this taxon, as an ordered list of taxonomic
         * ranks from least specific to most specific.
         *
         * @example
         *
         * Life
         *   Domain
         *     Kingdom
         *       Phylum
         *         Clas
         *           Order
         *             Family
         *               Genus
         *                 Species
         *
         */
        function scientific_lineage() {
            return client().get_scientific_lineage(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {String}
         */
        function scientific_name() {
            return Promise.try(function () {
                return client().get_scientific_name(authToken, objectReference, true)
                    .catch(taxon.AttributeException, function (err) {
                        return undefined;
                    });;
            });
        }

        /**
         *
         * @returns {Number}
         */
        function taxonomic_id() {
            return client().get_taxonomic_id(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {String}
         */
        function kingdom() {
            return client().get_kingdom(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {String}
         */
        function domain() {
            return client().get_domain(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         * The NCBI genetic code for the species.
         *
         * @returns {Number}
         * @see {@link http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi} NCBI "The Genetic Codes"
         */
        function genetic_code() {
            return client().get_genetic_code(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        /**
         *
         * @returns {Array<String>}
         */
        function aliases() {
            return client().get_aliases(authToken, objectReference, true)
                .catch(taxon.AttributeException, function (err) {
                    return undefined;
                });
        }

        // API
        return Object.freeze({
            parent: parent,
            children: children,
            genome_annotations: genome_annotations,
            scientific_lineage: scientific_lineage,
            scientific_name: scientific_name,
            taxonomic_id: taxonomic_id,
            kingdom: kingdom,
            domain: domain,
            genetic_code: genetic_code,
            aliases: aliases
        });
    };

    var api = {
        client: function (config) {
            return makeTaxonClient(config);
        },
        ClientException: common.ClientException,
        ServiceException: taxon.ServiceException,
        AuthorizationException: taxon.AuthorizationException,
        AuthenticationException: taxon.AuthenticationException,
        ObjectReferenceException: taxon.ObjectReferenceException,
        AttributeException: taxon.AttributeException,
        TypeException: taxon.TypeException
    };

    for (var propKey in Thrift) {
        if (propKey.match(/Exception$/)) {
            api[propKey] = Thrift[propKey];
        }
    }
    return Object.freeze(api);
});<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc directive
 * @name switchviewApp.directive:switchview
 * @description Usage <switch-view data='device'></switch-view> will render with defaults. To override use following format:
 <switch-view data='device' margin='10' port-height='42' port-width='44' padding='6'></switch-view>
 * # switchview
 */

angular.module('flowsimUiApp').
    directive('switchView', ['$window', 'portsView',
        function ($window, portsView) {
            return {
                restrict: 'EA',
                scope: {
                    data: '=',
                    label: '@',
                    onClick: '&'
                },
                link: function (scope, ele, attrs) {

                    scope.isColorA = function (i, j) {
                        return j % 2 === 0 && i % 2 === 0 || j % 2 !== 0 && i % 2 !== 0;
                    };
                    //directive attributes with deafults
                    var margin = parseInt(attrs.margin) || 3,
                        portHeight = parseInt(attrs.portHeight) || 20,
                        portWidth = parseInt(attrs.portWidth) || 22,
                        portPadding = parseInt(attrs.portPadding) || 3;

                    var svg = d3.select(ele[0])
                        .append('svg')
                        .attr('height', portHeight + 3 * margin)
                        .attr('width', 0)
                        .attr('class', 'Switch');

                    $window.onresize = function () {
                        scope.$apply();
                    };

                    scope.$watch(function () {
                        return angular.element($window)[0].innerWidth;
                    }, function () {
                        scope.render(scope.data);
                    });

                    scope.$watch('data', function (newData) {
                        //scope.ports = portsView(newData.ports, 24);
                        scope.render(scope.data);
                    }, true);

                    /**
                     * Main rendering function. Accept Device object.
                     * @param data - device object. e.g.{ n_ports: 0, ports: []}
                     */
                    scope.render = function (data) {
                        svg.selectAll('*').remove();//cleanup

                        if (_.isUndefined(data) || !data || data.length === 0) {
                          return; //don't render if there is no data
                        }
                        data = portsView(data.ports, 24);//parse ports and convert to matrix [row][port]

                        //dimensions of the SVG container
                        var height = data.length * portHeight + 3 * margin,
                            width = data[0].length * (portWidth + portPadding) + margin;
                        svg.attr('height', height)
                            .attr('width', width);
                        //Add group elements per switch row
                        _.each(data, function (row, i) {
                            svg.append('g')
                                .style('width', '100%')
                                .attr('index', i);
                        });

                        var portsG = svg.selectAll('g')
                            .data(data)
                            .selectAll('g')
                            .data(function (d) {
                                return d;
                            })
                            .enter()
                            .append('g')
                            .on('click', function (d) {
                                return scope.onClick({item: d});
                            })
                            .attr('height', portHeight)
                            .attr('width', portWidth)
                            .attr('class', function (d, i) {
                                return (scope.isColorA(this.parentNode.attributes.index.value, i) ? 'PortColorA' : 'PortColorB');
                            })
                            .style('opacity', function (d) {
                                return d.state.link_down ? 0.3 : 1;
                            })
                            .attr('transform', function (d, i) {
                                var x = i * (portWidth + portPadding) + margin;
                                var y = this.parentNode.attributes.index.value * (portHeight + portPadding) + margin;
                                return 'translate(' + x + ',' + y + ')';
                            });
//Copper shape
                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Copper';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.85)
                            .attr('width', portWidth)
                            .attr('ry', 2)
                            .attr('y', portHeight * 0.15);

                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Copper';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.15)
                            .attr('width', portWidth * 0.4)
                            .attr('x', portWidth * 0.3);

//Fiber Shape
                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Fiber';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.8)
                            .attr('width', portWidth / 2 - 1)
                            .attr('ry', 2)
                            .attr('y', portHeight * 0.15);

                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Fiber';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.8)
                            .attr('width', portWidth / 2 - 1)
                            .attr('ry', 2)
                            .attr('y', portHeight * 0.15)
                            .attr('x', portWidth / 2 + 2);

                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Fiber';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.6)
                            .attr('width', portWidth * 0.6)
                            .attr('x', portWidth * 0.2)
                            .attr('y', portHeight * 0.1);

//Text
                        portsG.append('text')
                            .attr('y', 14)
                            .attr('x', 11)
                            .attr('class', 'PortText')
                            .attr('text-anchor', 'middle')
                            .text(function (d) {
                                return d.id;
                            });
                    };

                }};
        }]);
<commit_msg>switch gui adjustment<commit_after>'use strict';

/**
 * @ngdoc directive
 * @name switchviewApp.directive:switchview
 * @description Usage <switch-view data='device'></switch-view> will render with defaults. To override use following format:
 <switch-view data='device' margin='10' port-height='42' port-width='44' padding='6'></switch-view>
 * # switchview
 */

angular.module('flowsimUiApp').
    directive('switchView', ['$window', 'portsView',
        function ($window, portsView) {
            return {
                restrict: 'EA',
                scope: {
                    data: '=',
                    label: '@',
                    onClick: '&'
                },
                link: function (scope, ele, attrs) {

                    scope.isColorA = function (i, j) {
                        return j % 2 === 0 && i % 2 === 0 || j % 2 !== 0 && i % 2 !== 0;
                    };
                    //directive attributes with deafults
                    var margin = parseInt(attrs.margin) || 3,
                        portHeight = parseInt(attrs.portHeight) || 20,
                        portWidth = parseInt(attrs.portWidth) || 22,
                        portPadding = parseInt(attrs.portPadding) || 3;

                    var svg = d3.select(ele[0])
                        .append('svg')
                        .attr('height', portHeight + 3 * margin)
                        .attr('width', 0)
                        .attr('class', 'Switch');

                    $window.onresize = function () {
                        scope.$apply();
                    };

                    scope.$watch(function () {
                        return angular.element($window)[0].innerWidth;
                    }, function () {
                        scope.render(scope.data);
                    });

                    scope.$watch('data', function (newData) {
                        //scope.ports = portsView(newData.ports, 24);
                        scope.render(scope.data);
                    }, true);

                    /**
                     * Main rendering function. Accept Device object.
                     * @param data - device object. e.g.{ n_ports: 0, ports: []}
                     */
                    scope.render = function (data) {
                        svg.selectAll('*').remove();//cleanup

                        if (_.isUndefined(data) || !data || data.length === 0) {
                          return; //don't render if there is no data
                        }
                        data = portsView(data.ports, 24);//parse ports and convert to matrix [row][port]

                        //dimensions of the SVG container
                        var height = data.length * (portHeight + margin),
                            width = data[0].length * (portWidth + portPadding) + margin;
                        svg.attr('height', height)
                            .attr('width', width);
                        //Add group elements per switch row
                        _.each(data, function (row, i) {
                            svg.append('g')
                                .style('width', '100%')
                                .attr('index', i);
                        });

                        var portsG = svg.selectAll('g')
                            .data(data)
                            .selectAll('g')
                            .data(function (d) {
                                return d;
                            })
                            .enter()
                            .append('g')
                            .on('click', function (d) {
                                return scope.onClick({item: d});
                            })
                            .attr('height', portHeight)
                            .attr('width', portWidth)
                            .attr('class', function (d, i) {
                                return (scope.isColorA(this.parentNode.attributes.index.value, i) ? 'PortColorA' : 'PortColorB');
                            })
                            .style('opacity', function (d) {
                                return d.state.link_down ? 0.3 : 1;
                            })
                            .attr('transform', function (d, i) {
                                var x = i * (portWidth + portPadding) + margin;
                                var y = this.parentNode.attributes.index.value * (portHeight + portPadding) + margin;
                                return 'translate(' + x + ',' + y + ')';
                            });
//Copper shape
                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Copper';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.85)
                            .attr('width', portWidth)
                            .attr('ry', 2)
                            .attr('y', portHeight * 0.15);

                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Copper';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.15)
                            .attr('width', portWidth * 0.4)
                            .attr('x', portWidth * 0.3);

//Fiber Shape
                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Fiber';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.8)
                            .attr('width', portWidth / 2 - 1)
                            .attr('ry', 2)
                            .attr('y', portHeight * 0.15);

                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Fiber';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.8)
                            .attr('width', portWidth / 2 - 1)
                            .attr('ry', 2)
                            .attr('y', portHeight * 0.15)
                            .attr('x', portWidth / 2 + 2);

                        portsG.filter(function (d) {
                            return d.ethernet.medium === 'Fiber';
                        })
                            .append('rect')
                            .attr('height', portHeight * 0.6)
                            .attr('width', portWidth * 0.6)
                            .attr('x', portWidth * 0.2)
                            .attr('y', portHeight * 0.1);

//Text
                        portsG.append('text')
                            .attr('y', 14)
                            .attr('x', 11)
                            .attr('class', 'PortText')
                            .attr('text-anchor', 'middle')
                            .text(function (d) {
                                return d.id;
                            });
                    };

                }};
        }]);
<|endoftext|>


<commit_before>export function forEach(arrayLike, iteratee){
  return Array.prototype.forEach.call(arrayLike, iteratee);
}

export function $(selector){
  return document.querySelectorAll(selector);
}

export function px(value){
  return value + 'px';
}<commit_msg>Add createElement function.<commit_after>export function forEach(arrayLike, iteratee){
  return Array.prototype.forEach.call(arrayLike, iteratee);
}

export function $(selector){
  return document.querySelectorAll(selector);
}

export function px(value){
  return value + 'px';
}

export function createElement(type, id){
  var e = document.createElement(type);
  e.id = id;
  return e;
}<|endoftext|>


<commit_before>/*global require*/
var util = require('util'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    HtmlRelation = require('./HtmlRelation');

function HtmlDart(config) {
    HtmlRelation.call(this, config);
}

util.inherits(HtmlDart, HtmlRelation);

extendWithGettersAndSetters(HtmlDart.prototype, {
    get href() {
        return this.node.getAttribute('src');
    },

    set href(href) {
        this.node.setAttribute('src', href);
    },

    /**
     * Dart doesn’t support inline scripts (scripts defined inside the HTML page).
     * While an inline script technically works in Dartium (a build of Chromium with the Dart VM),
     * the Dart-to-JavaScript compiler (dart2js) doesn’t work with inline scripts.
     * https://www.dartlang.org/articles/embedding-in-html/
     */
    inline: function () {
        return this;
    },

    attach: function (asset, position, adjacentRelation) {
        this.node = asset.parseTree.createElement('script');
        this.node.setAttribute('type', this.to.contentType);
        if (position === 'first') {
            var existingScriptNodes = asset.parseTree.getElementsByTagName('script');
            if (existingScriptNodes.length > 0) {
                existingScriptNodes[0].parentNode.insertBefore(this.node, existingScriptNodes[0]);
            } else if (asset.parseTree.body) {
                asset.parseTree.body.insertBefore(this.node, asset.parseTree.body.firstChild);
            } else {
                asset.parseTree.head.appendChild(this.node);
            }
        } else {
            this.attachNodeBeforeOrAfter(position, adjacentRelation);
        }
        return HtmlRelation.prototype.attach.call(this, asset, position, adjacentRelation);
    }
});

module.exports = HtmlDart;
<commit_msg>HtmlDart relation now inherits from HtmlScript<commit_after>/*global require*/
var util = require('util'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    HtmlScript = require('./HtmlScript');

function HtmlDart(config) {
    HtmlScript.call(this, config);
}

util.inherits(HtmlDart, HtmlScript);

extendWithGettersAndSetters(HtmlDart.prototype, {
    get href() {
        return this.node.getAttribute('src');
    },

    /**
     * Dart doesn’t support inline scripts (scripts defined inside the HTML page).
     * While an inline script technically works in Dartium (a build of Chromium with the Dart VM),
     * the Dart-to-JavaScript compiler (dart2js) doesn’t work with inline scripts.
     * https://www.dartlang.org/articles/embedding-in-html/
     */
    inline: function () {
        return this;
    }
});

module.exports = HtmlDart;
<|endoftext|>


<commit_before>var mime = require("mime");
var busterPromise = require("buster-promise");
var minifyProcessor = require("./processors/minifier");

module.exports = {
    create: function (path, resource, resourceMiddleware) {
        var instance = Object.create(this);
        instance.path = path;

        if (typeof(resource) == "string") {
            instance.content = "lol";
            resource = resourceMiddleware.getResourceForPathWithEtag(path, resource);
        }

        instance.content = resource.content;
        instance.headers = resource.headers || {};
        instance.combine = resource.combine;
        instance.backend = resource.backend;
        if ("etag" in resource) {
            instance.etag = resource.etag;
        }

        instance.processors = [];

        if (resource.minify) {
            instance.processors.push(Object.create(minifyProcessor));
        }

        return instance;
    },

    getHeaders: function () {
        var headers = {};

        for (var header in this.headers) {
            headers[header] = this.headers[header];
        }

        if (!headers["Content-Type"]) {
            headers["Content-Type"] = mime.lookup(this.path);
        }

        return headers;
    },

    getContent: function () {
        var self = this;
        var promise = busterPromise.create();

        if (typeof(this.content) == "function") {
            var cPromise = busterPromise.create();
            this.content(cPromise);
            cPromise.then(function (content) {
                promise.resolve(self.applyFilters(content));
            }, function (err) {
                promise.reject(err);
            });
        } else {
            promise.resolve(this.applyFilters(this.content));
        }

        return promise;
    },

    applyFilters: function (content) {
        for (var i = 0, ii = this.processors.length; i < ii; i++) {
            content = this.processors[i].process(content);
        }

        return content;
    },

    addProcessor: function (processor) {
        this.processors.push(processor);
    }
};<commit_msg>Removing a piece of code that is not particularly useful to anyone.<commit_after>var mime = require("mime");
var busterPromise = require("buster-promise");
var minifyProcessor = require("./processors/minifier");

module.exports = {
    create: function (path, resource, resourceMiddleware) {
        var instance = Object.create(this);
        instance.path = path;

        if (typeof(resource) == "string") {
            resource = resourceMiddleware.getResourceForPathWithEtag(path, resource);
        }

        instance.content = resource.content;
        instance.headers = resource.headers || {};
        instance.combine = resource.combine;
        instance.backend = resource.backend;
        if ("etag" in resource) {
            instance.etag = resource.etag;
        }

        instance.processors = [];

        if (resource.minify) {
            instance.processors.push(Object.create(minifyProcessor));
        }

        return instance;
    },

    getHeaders: function () {
        var headers = {};

        for (var header in this.headers) {
            headers[header] = this.headers[header];
        }

        if (!headers["Content-Type"]) {
            headers["Content-Type"] = mime.lookup(this.path);
        }

        return headers;
    },

    getContent: function () {
        var self = this;
        var promise = busterPromise.create();

        if (typeof(this.content) == "function") {
            var cPromise = busterPromise.create();
            this.content(cPromise);
            cPromise.then(function (content) {
                promise.resolve(self.applyFilters(content));
            }, function (err) {
                promise.reject(err);
            });
        } else {
            promise.resolve(this.applyFilters(this.content));
        }

        return promise;
    },

    applyFilters: function (content) {
        for (var i = 0, ii = this.processors.length; i < ii; i++) {
            content = this.processors[i].process(content);
        }

        return content;
    },

    addProcessor: function (processor) {
        this.processors.push(processor);
    }
};<|endoftext|>


<commit_before>var path = require('path');

var config = {};
config.web = {};
config.redis = {};
config.siteops = {};
config.siteops.redis = {};

config.web.port = process.env.PORT || 3000;
config.web.webSocketUrl = null; // 'ws://localhost:9090/pubsub' for local Daemon
config.redis.host = null; // 'localhost' for local Redis server
config.redis.port = null; // 6379 is default Redis port
config.siteops.redis.host = null; // 'localhost' for local Redis server
config.siteops.redis.port = null; // 6379 is default Redis port

module.exports = config<commit_msg>#65 Ads Dimensions Demo - Redis Configuration<commit_after>var path = require('path');

var config = {};
config.web = {};
config.redis = {};
config.adsdimensions = {};
config.adsdimensions.redis = {};
config.siteops = {};
config.siteops.redis = {};

config.web.port = process.env.PORT || 3000;
config.web.webSocketUrl = null; // 'ws://localhost:9090/pubsub' for local Daemon
config.adsdimensions.redis.host = null; // 'localhost' for local Redis server
config.adsdimensions.redis.port = null; // 6379 is default Redis port
config.siteops.redis.host = null; // 'localhost' for local Redis server
config.siteops.redis.port = null; // 6379 is default Redis port

module.exports = config<|endoftext|>


<commit_before>var somethingWentWrong = $("#FailText").text();
$(function () {
    "use strict";
    function log (x) {
        return x;
    }
    function makeEditable(o) {
        o.saveState = ko.observable('saved');
        o.editing = ko.observable(false);
        o.startEditing = function () {
            o.editing(true);
            try {
                o._backup = o.serialize();
            } catch (e) {

            }
        };
        o.stopEdit = function () {
            o.editing(false);
        };
        o.cancelEdit = function () {
            o.editing(false);
            o.cancel();
        };
        o.saveEdit = function () {
            o.editing(false);
            log(o);
            o.save();
        };
        return o;
    }
    function makeDataType(o, app) {
        var self = ko.mapping.fromJS(o),
            raw_fields = self.fields();
            self.original_tag = self.tag();
            self.original_visibility = self.is_global();
        self.fields = ko.observableArray([]);
        makeEditable(self);
        if (!o._id) {
            self._id = ko.observable();
        }
        self.view_link = ko.computed(function(){
            return TableViewUrl + "?table_id="+self._id();
        }, self);
        self.aboutToDelete = ko.observable(false);
        self.addField = function (data, event, o) {
            var i, field;
            if (o) {
                field = {
                    tag: ko.observable(o.tag),
                    with_props: ko.observable(o.with_props),
                    original_tag: ko.observable(o.tag),
                    is_new: ko.observable(false),
                    remove: ko.observable(false),
                    editing: ko.observable(false)
                };
            } else {
                field = {
                    tag: ko.observable(""),
                    with_props: ko.observable(false),
                    original_tag: ko.observable(""),
                    is_new: ko.observable(true),
                    remove: ko.observable(false),
                    editing: ko.observable(true)
                };
            }
            field.remove_if_new = function(){
                if (field.is_new() == true){
                    self.fields.remove(field);
                }
            };
            field.editTag = ko.computed({
                read: function () {
                    return field.tag();
                },
                write: function (tag) {
                    var j, noRepeats = true;
                    for (j = 0; j < self.fields().length; j += 1) {
                        if (self.fields()[j].tag === tag) {
                            noRepeats = false;
                        }
                    }
                    if (noRepeats) {
                        var oldTag = field.tag;
                        field.tag(tag);
                    }
                }
            });
            self.fields.push(field);
        };
        for (var i = 0; i < raw_fields.length; i += 1) {
            var tag = raw_fields[i].field_name();
            var with_props = (raw_fields[i].properties().length == 0) ? false : true;
            self.addField(undefined, undefined, {tag: tag, with_props: with_props});
        }

        self.save = function () {
            $.ajax({
                type: self._id() ? (self._destroy ? 'delete' : 'put') : 'post',
                url: UpdateTableUrl + (self._id() || ''),
                data: JSON.stringify(self.serialize()),
                dataType: 'json',
                error: function(data) {
                    var error_message;
                    if (data.responseText == "DuplicateFixture"){
                        error_message = "Can not create table with table_id '"+self.tag()+"'. table_id should be unique.";
                    }
                    else{
                        error_message = somethingWentWrong;
                    }
                    $("#FailText").text(error_message);
                    $("#editFailure").show();
                    self.cancel();
                    self.saveState('saved');
                    },
                success: function (data) {
                    self.saveState('saved');
                    if (!self._id()) {
                        self._id(data._id);
                    }
                    self.original_visibility = self.is_global();
                    self.original_tag = self.tag();
                    var indicesToRemoveAt = [];
                    for (var i = 0; i < self.fields().length; i += 1) {
                        var field = self.fields()[i];
                        field.original_tag(field.tag());
                        field.is_new(false);
                        if (field.remove() == true){
                            indicesToRemoveAt.push(i);
                        }
                    }
                    for (var j = 0; j < indicesToRemoveAt.length; j += 1){
                        var index = indicesToRemoveAt[j]
                        self.fields.remove(self.fields()[index]);
                    }
                }
            });
            self.saveState('saving');
        };
        self.cancel = function () {
            var indicesToRemoveAt = [];
            self.tag(self.original_tag);
            self.is_global(self.original_visibility);
            if (!o._id()) {
                app.data_types.remove(self);
                return;
            }
            for (var i = 0; i < self.fields().length; i += 1) {
                var field = self.fields()[i];
                if (field.is_new() == true){
                    indicesToRemoveAt.push(i);
                    continue;
                }
                field.tag(field.original_tag());
                field.remove(false);
            }
            for (var j = 0; j < indicesToRemoveAt.length; j += 1){
                var index = indicesToRemoveAt[j]
                self.fields.remove(self.fields()[index]);
            }
        }
        self.serialize = function () {
            return log({
                _id: self._id(),
                tag: self.tag(),
                view_link: self.view_link(),
                is_global: self.is_global(),
                fields: (function () {
                    var fields = {}, i;
                    for (i = 0; i < self.fields().length; i += 1) {
                        var field = self.fields()[i];
                        var patch;
                        if (field.is_new() == true) {
                            if (field.remove() == true) continue;
                            patch = {"is_new": 1};
                            fields[field.tag()] = patch;
                        }
                        else if (field.remove() === true) {
                            patch = {"remove": 1};
                            fields[field.original_tag()] = patch;
                        }
                        else if (field.tag() !== field.original_tag()){
                            patch = {"update": field.tag()};
                            fields[field.original_tag()] = patch;
                        }
                        else {
                            patch = {};
                            fields[field.tag()] = patch;
                        }
                    }
                    return fields;
                }())
            });
        };
        return self;
    }
    function App() {
        var self = this;
        self.data_types = ko.observableArray([]);
        self.loading = ko.observable(0);
        self.selectedTables = ko.observableArray([]);

        self.updateSelectedTables = function(element, event) {
            var $elem = $(event.srcElement || event.currentTarget);
            var $checkboxes = $(".select-bulk");
            if ($elem.hasClass("toggle")){
                self.selectedTables.removeAll();
                if ($elem.data("all")) {
                    $.each($checkboxes, function() {
                        $(this).attr("checked", true);
                        self.selectedTables.push(this.value);
                    });
                }
                else {
                    $.each($checkboxes, function() {
                        $(this).attr("checked", false);
                    });
                }
            }
            if ($elem.hasClass("select-bulk")) {
                var table_id = $elem[0].value;
                if ($elem[0].checked) {
                    self.selectedTables.push(table_id);
                }
                else {
                    self.selectedTables.splice(self.selectedTables().indexOf(table_id), 1);
                }
            }
        };

        self.downloadExcels = function(element, event) {
            var tables = [];
            var FixtureUrl = FixtureDownloadUrl;
            if (self.selectedTables().length < 1)
                return;
            for (var i in self.selectedTables()) {
                tables.push(self.selectedTables()[i]);
                FixtureUrl = FixtureUrl + "table_id=" + self.selectedTables()[i] + "&";
            }
            $("#fixture-download").modal();
            if (tables.length > 0){
                $.ajax({
                    url: FixtureUrl,
                    dataType: 'json',
                    success: function (response) {
                        $("#downloading").hide();
                        $("#download-complete").show();
                        $("#file-download-url").attr("href", FixtureFileDownloadUrl + "download_id=" + response.download_id);
                    },
                    error: function (response) {
                        var error_message = "Sorry, something went wrong with the download. If you see this repeatedly please report an issue."
                        $("#fixture-download").modal("hide");
                        $("#FailText").text(error_message);
                        $("#editFailure").show();
                    }
                });
            }

        };

        self.addDataType = function () {
            var dataType = makeDataType({
                tag: "",
                fields: ko.observableArray([]),
                is_global: false,
            }, self);
            dataType.editing(true);
            self.data_types.push(dataType);
        };
        self.removeDataType = function (dataType) {
            if (confirm("Are you sure you want to delete the table '" + dataType.tag() + "'")){
                    self.data_types.destroy(dataType);
                    dataType.save();
            }
            return false;
        };
        self.loadData = function () {
            self.loading(self.loading() + 3);
            $.ajax({
                url: DataTypeUrl,
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    var dataType;
                    for (var i = 0; i < data.length; i += 1) {
                        self.data_types.push(makeDataType(data[i], self));
                        dataType = self.data_types()[i];
                    }
                    self.loading(self.loading() - 1);
                }
            });
        };
    }

    var el = $('#fixtures-ui');
    var app = new App();
    ko.applyBindings(app, el.get(0));
    el.show();
    app.loadData();

    $("#fixture-download").on("hidden", function(){
                    $("#downloading").show();
                    $("#download-complete").hide();
    });
    $('.alert .close').live("click", function(e) {
        $(this).parent().hide();

    });
});<commit_msg>restore functionality to disable upload button until a file is selected<commit_after>var somethingWentWrong = $("#FailText").text();
$(function () {
    "use strict";
    function log (x) {
        return x;
    }
    function makeEditable(o) {
        o.saveState = ko.observable('saved');
        o.editing = ko.observable(false);
        o.startEditing = function () {
            o.editing(true);
            try {
                o._backup = o.serialize();
            } catch (e) {

            }
        };
        o.stopEdit = function () {
            o.editing(false);
        };
        o.cancelEdit = function () {
            o.editing(false);
            o.cancel();
        };
        o.saveEdit = function () {
            o.editing(false);
            log(o);
            o.save();
        };
        return o;
    }
    function makeDataType(o, app) {
        var self = ko.mapping.fromJS(o),
            raw_fields = self.fields();
            self.original_tag = self.tag();
            self.original_visibility = self.is_global();
        self.fields = ko.observableArray([]);
        makeEditable(self);
        if (!o._id) {
            self._id = ko.observable();
        }
        self.view_link = ko.computed(function(){
            return TableViewUrl + "?table_id="+self._id();
        }, self);
        self.aboutToDelete = ko.observable(false);
        self.addField = function (data, event, o) {
            var i, field;
            if (o) {
                field = {
                    tag: ko.observable(o.tag),
                    with_props: ko.observable(o.with_props),
                    original_tag: ko.observable(o.tag),
                    is_new: ko.observable(false),
                    remove: ko.observable(false),
                    editing: ko.observable(false)
                };
            } else {
                field = {
                    tag: ko.observable(""),
                    with_props: ko.observable(false),
                    original_tag: ko.observable(""),
                    is_new: ko.observable(true),
                    remove: ko.observable(false),
                    editing: ko.observable(true)
                };
            }
            field.remove_if_new = function(){
                if (field.is_new() == true){
                    self.fields.remove(field);
                }
            };
            field.editTag = ko.computed({
                read: function () {
                    return field.tag();
                },
                write: function (tag) {
                    var j, noRepeats = true;
                    for (j = 0; j < self.fields().length; j += 1) {
                        if (self.fields()[j].tag === tag) {
                            noRepeats = false;
                        }
                    }
                    if (noRepeats) {
                        var oldTag = field.tag;
                        field.tag(tag);
                    }
                }
            });
            self.fields.push(field);
        };
        for (var i = 0; i < raw_fields.length; i += 1) {
            var tag = raw_fields[i].field_name();
            var with_props = (raw_fields[i].properties().length == 0) ? false : true;
            self.addField(undefined, undefined, {tag: tag, with_props: with_props});
        }

        self.save = function () {
            $.ajax({
                type: self._id() ? (self._destroy ? 'delete' : 'put') : 'post',
                url: UpdateTableUrl + (self._id() || ''),
                data: JSON.stringify(self.serialize()),
                dataType: 'json',
                error: function(data) {
                    var error_message;
                    if (data.responseText == "DuplicateFixture"){
                        error_message = "Can not create table with table_id '"+self.tag()+"'. table_id should be unique.";
                    }
                    else{
                        error_message = somethingWentWrong;
                    }
                    $("#FailText").text(error_message);
                    $("#editFailure").show();
                    self.cancel();
                    self.saveState('saved');
                    },
                success: function (data) {
                    self.saveState('saved');
                    if (!self._id()) {
                        self._id(data._id);
                    }
                    self.original_visibility = self.is_global();
                    self.original_tag = self.tag();
                    var indicesToRemoveAt = [];
                    for (var i = 0; i < self.fields().length; i += 1) {
                        var field = self.fields()[i];
                        field.original_tag(field.tag());
                        field.is_new(false);
                        if (field.remove() == true){
                            indicesToRemoveAt.push(i);
                        }
                    }
                    for (var j = 0; j < indicesToRemoveAt.length; j += 1){
                        var index = indicesToRemoveAt[j]
                        self.fields.remove(self.fields()[index]);
                    }
                }
            });
            self.saveState('saving');
        };
        self.cancel = function () {
            var indicesToRemoveAt = [];
            self.tag(self.original_tag);
            self.is_global(self.original_visibility);
            if (!o._id()) {
                app.data_types.remove(self);
                return;
            }
            for (var i = 0; i < self.fields().length; i += 1) {
                var field = self.fields()[i];
                if (field.is_new() == true){
                    indicesToRemoveAt.push(i);
                    continue;
                }
                field.tag(field.original_tag());
                field.remove(false);
            }
            for (var j = 0; j < indicesToRemoveAt.length; j += 1){
                var index = indicesToRemoveAt[j]
                self.fields.remove(self.fields()[index]);
            }
        }
        self.serialize = function () {
            return log({
                _id: self._id(),
                tag: self.tag(),
                view_link: self.view_link(),
                is_global: self.is_global(),
                fields: (function () {
                    var fields = {}, i;
                    for (i = 0; i < self.fields().length; i += 1) {
                        var field = self.fields()[i];
                        var patch;
                        if (field.is_new() == true) {
                            if (field.remove() == true) continue;
                            patch = {"is_new": 1};
                            fields[field.tag()] = patch;
                        }
                        else if (field.remove() === true) {
                            patch = {"remove": 1};
                            fields[field.original_tag()] = patch;
                        }
                        else if (field.tag() !== field.original_tag()){
                            patch = {"update": field.tag()};
                            fields[field.original_tag()] = patch;
                        }
                        else {
                            patch = {};
                            fields[field.tag()] = patch;
                        }
                    }
                    return fields;
                }())
            });
        };
        return self;
    }
    function App() {
        var self = this;
        self.data_types = ko.observableArray([]);
        self.loading = ko.observable(0);
        self.file = ko.observable();
        self.selectedTables = ko.observableArray([]);

        self.updateSelectedTables = function(element, event) {
            var $elem = $(event.srcElement || event.currentTarget);
            var $checkboxes = $(".select-bulk");
            if ($elem.hasClass("toggle")){
                self.selectedTables.removeAll();
                if ($elem.data("all")) {
                    $.each($checkboxes, function() {
                        $(this).attr("checked", true);
                        self.selectedTables.push(this.value);
                    });
                }
                else {
                    $.each($checkboxes, function() {
                        $(this).attr("checked", false);
                    });
                }
            }
            if ($elem.hasClass("select-bulk")) {
                var table_id = $elem[0].value;
                if ($elem[0].checked) {
                    self.selectedTables.push(table_id);
                }
                else {
                    self.selectedTables.splice(self.selectedTables().indexOf(table_id), 1);
                }
            }
        };

        self.downloadExcels = function(element, event) {
            var tables = [];
            var FixtureUrl = FixtureDownloadUrl;
            if (self.selectedTables().length < 1)
                return;
            for (var i in self.selectedTables()) {
                tables.push(self.selectedTables()[i]);
                FixtureUrl = FixtureUrl + "table_id=" + self.selectedTables()[i] + "&";
            }
            $("#fixture-download").modal();
            if (tables.length > 0){
                $.ajax({
                    url: FixtureUrl,
                    dataType: 'json',
                    success: function (response) {
                        $("#downloading").hide();
                        $("#download-complete").show();
                        $("#file-download-url").attr("href", FixtureFileDownloadUrl + "download_id=" + response.download_id);
                    },
                    error: function (response) {
                        var error_message = "Sorry, something went wrong with the download. If you see this repeatedly please report an issue."
                        $("#fixture-download").modal("hide");
                        $("#FailText").text(error_message);
                        $("#editFailure").show();
                    }
                });
            }

        };

        self.addDataType = function () {
            var dataType = makeDataType({
                tag: "",
                fields: ko.observableArray([]),
                is_global: false
            }, self);
            dataType.editing(true);
            self.data_types.push(dataType);
        };
        self.removeDataType = function (dataType) {
            if (confirm("Are you sure you want to delete the table '" + dataType.tag() + "'")){
                    self.data_types.destroy(dataType);
                    dataType.save();
            }
            return false;
        };
        self.loadData = function () {
            self.loading(self.loading() + 3);
            $.ajax({
                url: DataTypeUrl,
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    var dataType;
                    for (var i = 0; i < data.length; i += 1) {
                        self.data_types.push(makeDataType(data[i], self));
                        dataType = self.data_types()[i];
                    }
                    self.loading(self.loading() - 1);
                }
            });
        };
    }

    var el = $('#fixtures-ui');
    var app = new App();
    ko.applyBindings(app, el.get(0));
    el.show();
    app.loadData();
    ko.applyBindings(app, $('#fixture-upload')[0]);
    $("#fixture-download").on("hidden", function(){
                    $("#downloading").show();
                    $("#download-complete").hide();
    });
    $('.alert .close').live("click", function(e) {
        $(this).parent().hide();

    });
});<|endoftext|>


<commit_before>Vps.Form.GoogleMapWindow = Ext.extend(Ext.Window,
{
    initComponent: function() {
		this.addEvents('confirm');
		this.addEvents('clear');

		this.actions = {};
		this.actions.clear = new Ext.Action({
			text:'Clear',
			handler: function() {
				this.clear = true;
				this.fireEvent('clear', this);
				this.hide();
			},
			icon    : '/assets/silkicons/bin_closed.png',
			cls     : 'x-btn-text-icon',
			scope : this}
		);

		this.tbar = [{}];
		this.tbar.add(
			this.actions.clear,
			'->', {
			text:'Search',
			handler: this.addressPrompt,
			icon    : '/assets/silkicons/find.png',
			cls     : 'x-btn-text-icon',
			scope : this
		});

		this.buttons = [
		{
			text: 'Cancel',
			handler: function() {
				this.hide();
			},
			scope: this
		},{
			text: 'Ok',
			handler: function() {
				this.clear = false;
				this.fireEvent('confirm', this);
				this.hide();
			},
			scope: this
		}];
		Vps.Form.GoogleMapWindow.superclass.initComponent.call(this);
	},
	afterRender:function(){
		Vps.Form.GoogleMapWindow.superclass.afterRender.call(this);
	    this.map = new GMap2(this.body.dom);
		this.geocoder = new GClientGeocoder();
		this.map.addControl(new GLargeMapControl());
        this.map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(64,15)));
        this.map.addControl(new GMapTypeControl());
        this.map.addControl(new GOverviewMapControl());

		var point = new GLatLng(47.9534, 13.2448);
        this.marker = new GMarker(point, {draggable: true});

		this.setMarkerPoint ('47.9534;13.2448');

		GEvent.addListener(this.marker, 'click',     this.showLatLng.createDelegate(this));
        GEvent.addListener(this.marker, 'dragstart', this.hideLatLng.createDelegate(this));
        GEvent.addListener(this.marker, 'dragend',   this.showLatLng.createDelegate(this));
    },
	addressPrompt:function(){
		Ext.Msg.prompt(trlVps('enter address'), trlVps('Example: Pfongauerstraße 67, 5202 Neumarkt am Wallersee'), function(btn, text){
		    if (btn == 'ok' && text != ''){
		        this.geoCodeLookup(text);
		    }
		}, this);
	},
	geoCodeLookup : function(address) {
	    this.geocoder.getLocations(address, this.addAddressToMap.createDelegate(this));
	},
	addAddressToMap : function(response) {
		this.placemarks = response.Placemark;
		if (!response || response.Status.code != 200) {
			Ext.MessageBox.alert(trlVps('Error'), trlVps('Code {0} Error Returned', [response.Status.code]));
			} else {
			place = response.Placemark[0];
			addressinfo = place.AddressDetails;
			accuracy = addressinfo.Accuracy;
			if (accuracy == 0) {
				Ext.MessageBox.alert(trlVps('Unknown address'), trlVps('Address could not be found'));
			}else{
				if (accuracy < 7) {
					var myData = [];
					for (var i=0; i<this.placemarks.length; i++) {
                        if (!this.placemarks[i]) { break; }
						var tempPush = [this.placemarks[i].address];
                        myData.push(tempPush);
                    }

					var store = new Ext.data.SimpleStore({
				        fields: [
				           {name: 'address'}
				        ]
				    });
				    store.loadData(myData);

					var grid = new Ext.grid.GridPanel({
						store:store,
						columns: [
							{id: 'address', header: "Adressen", width: 300, sortable:false, dataIndex: 'address'}
						]
					});
					grid.on('rowdblclick', function(grid, index) {
						win.close();
						this.setMarkerPoint(this.placemarks[index].Point.coordinates[1]+';'+this.placemarks[index].Point.coordinates[0]);
					}, this);
					grid.on('rowmousedown', function(grid, index) {
						this.setMarkerPoint(this.placemarks[index].Point.coordinates[1]+';'+this.placemarks[index].Point.coordinates[0]);
					}, this);

					var win = new Ext.Window({
						modal: true,
						title: 'Mögliche Standorte',
						width:400,
						height:250,
						shadow:true,
						closeAction: 'close',
						layout: 'fit',
						buttons: [{
							text: 'Ok',
							handler: function() {
								win.close();
							},
							scope: this
						}],
						items: [grid]
            		});
					win.show();
				} else {
					this.setMarkerPoint(place.Point.coordinates[1]+';'+place.Point.coordinates[0]);
				}
			}
	  	}
    },
	showLatLng:function(){
		var pnt = this.marker.getPoint();
        pnt.y = Math.round(pnt.y * 100000000) / 100000000;
        pnt.x = Math.round(pnt.x * 100000000) / 100000000;
		this.markerpoint_x = pnt.x;
		this.markerpoint_y = pnt.y;
        this.marker.openInfoWindowHtml(trlVps('Move marker while pressing mousekey.')+'

' +
				trlVps('Latitude: ')+ pnt.y +'
'+trlVps('Longitude: ')+ pnt.x);
	},
	hideLatLng:function(){
		this.marker.closeInfoWindow();
	},
	setMarkerPoint:function(value){
		var points = value.split(";")
		this.markerpoint_y = points[0];
		this.markerpoint_x = points[1];
		if (this.markerpoint_y && this.markerpoint_x){
			this.map.setCenter(new GLatLng(this.markerpoint_y,this.markerpoint_x), 13);
			this.marker.setLatLng(new GLatLng(this.markerpoint_y,this.markerpoint_x));
			this.marker.closeInfoWindow();
			this.map.clearOverlays();
			this.map.addOverlay(this.marker);
			this.showLatLng();
		} else {
			this.addressPrompt();
		}

	},
	getMarkerPoint:function(){
		if (this.clear == true){
			this.clear = false;
			return "";
		}
		var pnt = this.marker.getPoint();
        pnt.y = Math.round(pnt.y * 100000000) / 100000000;
        pnt.x = Math.round(pnt.x * 100000000) / 100000000;
		return  pnt.y +';'+pnt.x;
	},
	setHideClearButton:function(check){
		if (check) {
			this.actions.clear.hide();
		} else {
			this.actions.clear.show();
		}
	}
});<commit_msg>Anders formatiert, jetzt kommt Übersetzungsfehler nicht mehr<commit_after>Vps.Form.GoogleMapWindow = Ext.extend(Ext.Window,
{
    initComponent: function() {
        this.addEvents('confirm');
        this.addEvents('clear');

        this.actions = {};
        this.actions.clear = new Ext.Action({
            text:'Clear',
            handler: function() {
                this.clear = true;
                this.fireEvent('clear', this);
                this.hide();
            },
            icon    : '/assets/silkicons/bin_closed.png',
            cls     : 'x-btn-text-icon',
            scope : this}
        );

        this.tbar = [{}];
        this.tbar.add(
            this.actions.clear,
            '->', {
            text:'Search',
            handler: this.addressPrompt,
            icon    : '/assets/silkicons/find.png',
            cls     : 'x-btn-text-icon',
            scope : this
        });

        this.buttons = [
        {
            text: 'Cancel',
            handler: function() {
                this.hide();
            },
            scope: this
        },{
            text: 'Ok',
            handler: function() {
                this.clear = false;
                this.fireEvent('confirm', this);
                this.hide();
            },
            scope: this
        }];
        Vps.Form.GoogleMapWindow.superclass.initComponent.call(this);
    },
    afterRender:function(){
        Vps.Form.GoogleMapWindow.superclass.afterRender.call(this);
        this.map = new GMap2(this.body.dom);
        this.geocoder = new GClientGeocoder();
        this.map.addControl(new GLargeMapControl());
        this.map.addControl(new GScaleControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(64,15)));
        this.map.addControl(new GMapTypeControl());
        this.map.addControl(new GOverviewMapControl());

        var point = new GLatLng(47.9534, 13.2448);
        this.marker = new GMarker(point, {draggable: true});

        this.setMarkerPoint ('47.9534;13.2448');

        GEvent.addListener(this.marker, 'click',     this.showLatLng.createDelegate(this));
        GEvent.addListener(this.marker, 'dragstart', this.hideLatLng.createDelegate(this));
        GEvent.addListener(this.marker, 'dragend',   this.showLatLng.createDelegate(this));
    },
    addressPrompt:function(){
        Ext.Msg.prompt(trlVps('enter address'), trlVps('Example: Pfongauerstraße 67, 5202 Neumarkt am Wallersee'), function(btn, text){
            if (btn == 'ok' && text != ''){
                this.geoCodeLookup(text);
            }
        }, this);
    },
    geoCodeLookup : function(address) {
        this.geocoder.getLocations(address, this.addAddressToMap.createDelegate(this));
    },
    addAddressToMap : function(response) {
        this.placemarks = response.Placemark;
        if (!response || response.Status.code != 200) {
                Ext.MessageBox.alert(
                    trlVps('Error'),
                    trlVps('Code {0} Error Returned', [response.Status.code])
                );
            } else {
            place = response.Placemark[0];
            addressinfo = place.AddressDetails;
            accuracy = addressinfo.Accuracy;
            if (accuracy == 0) {
                Ext.MessageBox.alert(trlVps('Unknown address'), trlVps('Address could not be found'));
            }else{
                if (accuracy < 7) {
                    var myData = [];
                    for (var i=0; i<this.placemarks.length; i++) {
                        if (!this.placemarks[i]) { break; }
                        var tempPush = [this.placemarks[i].address];
                        myData.push(tempPush);
                    }

                    var store = new Ext.data.SimpleStore({
                        fields: [
                        {name: 'address'}
                        ]
                    });
                    store.loadData(myData);

                    var grid = new Ext.grid.GridPanel({
                        store:store,
                        columns: [
                            {id: 'address', header: "Adressen", width: 300, sortable:false, dataIndex: 'address'}
                        ]
                    });
                    grid.on('rowdblclick', function(grid, index) {
                        win.close();
                        this.setMarkerPoint(this.placemarks[index].Point.coordinates[1]+';'+this.placemarks[index].Point.coordinates[0]);
                    }, this);
                    grid.on('rowmousedown', function(grid, index) {
                        this.setMarkerPoint(this.placemarks[index].Point.coordinates[1]+';'+this.placemarks[index].Point.coordinates[0]);
                    }, this);

                    var win = new Ext.Window({
                        modal: true,
                        title: 'Mögliche Standorte',
                        width:400,
                        height:250,
                        shadow:true,
                        closeAction: 'close',
                        layout: 'fit',
                        buttons: [{
                            text: 'Ok',
                            handler: function() {
                                win.close();
                            },
                            scope: this
                        }],
                        items: [grid]
                    });
                    win.show();
                } else {
                    this.setMarkerPoint(place.Point.coordinates[1]+';'+place.Point.coordinates[0]);
                }
            }
        }
    },
    showLatLng:function(){
        var pnt = this.marker.getPoint();
        pnt.y = Math.round(pnt.y * 100000000) / 100000000;
        pnt.x = Math.round(pnt.x * 100000000) / 100000000;
        this.markerpoint_x = pnt.x;
        this.markerpoint_y = pnt.y;
        this.marker.openInfoWindowHtml(trlVps('Move marker while pressing mousekey.')+'

' +
                trlVps('Latitude: ')+ pnt.y +'
'+trlVps('Longitude: ')+ pnt.x);
    },
    hideLatLng:function(){
        this.marker.closeInfoWindow();
    },
    setMarkerPoint:function(value){
        var points = value.split(";")
        this.markerpoint_y = points[0];
        this.markerpoint_x = points[1];
        if (this.markerpoint_y && this.markerpoint_x){
            this.map.setCenter(new GLatLng(this.markerpoint_y,this.markerpoint_x), 13);
            this.marker.setLatLng(new GLatLng(this.markerpoint_y,this.markerpoint_x));
            this.marker.closeInfoWindow();
            this.map.clearOverlays();
            this.map.addOverlay(this.marker);
            this.showLatLng();
        } else {
            this.addressPrompt();
        }

    },
    getMarkerPoint:function(){
        if (this.clear == true){
            this.clear = false;
            return "";
        }
        var pnt = this.marker.getPoint();
        pnt.y = Math.round(pnt.y * 100000000) / 100000000;
        pnt.x = Math.round(pnt.x * 100000000) / 100000000;
        return  pnt.y +';'+pnt.x;
    },
    setHideClearButton:function(check){
        if (check) {
            this.actions.clear.hide();
        } else {
            this.actions.clear.show();
        }
    }
});<|endoftext|>


<commit_before>function extractIdsFromSimplePattern(pattern) {
  if (pattern === undefined) {
    return []
  }

  if (pattern === null || typeof pattern !== 'object') {
    return
  }
  let keys = Object.keys(pattern)

  if (keys.length !== 1 || keys[0] !== 'id') {
    return
  }

  pattern = pattern.id
  if (typeof pattern === 'string') {
    return [pattern]
  }
  if (pattern === null || typeof pattern !== 'object') {
    return
  }

  keys = Object.keys(pattern)
  if (
    keys.length === 1 &&
    keys[0] === '__or' &&
    Array.isArray((pattern = pattern.__or)) &&
    pattern.every(_ => typeof _ === 'string')
  ) {
    return pattern
  }
}
exports.extractIdsFromSimplePattern = extractIdsFromSimplePattern
<commit_msg>feat(backups/extractIdsFromSimplePattern): throw on invalid pattern<commit_after>function extractIdsFromSimplePattern(pattern) {
  if (pattern === undefined) {
    return []
  }

  if (pattern !== null && typeof pattern === 'object') {
    let keys = Object.keys(pattern)

    if (keys.length === 1 && keys[0] === 'id') {
      pattern = pattern.id
      if (typeof pattern === 'string') {
        return [pattern]
      }
      if (pattern !== null && typeof pattern === 'object') {
        keys = Object.keys(pattern)
        if (
          keys.length === 1 &&
          keys[0] === '__or' &&
          Array.isArray((pattern = pattern.__or)) &&
          pattern.every(_ => typeof _ === 'string')
        ) {
          return pattern
        }
      }
    }
  }

  throw new Error('invalid pattern')
}
exports.extractIdsFromSimplePattern = extractIdsFromSimplePattern
<|endoftext|>


<commit_before>var Issue = require('../issue');
var lodash = require('lodash');

module.exports = {
  name: 'wcag-rule-38',
  on: ['tag'],
  filter: ['a'],
  desc: [
    'a rule from WCAG',
    'only triggers if the link has a link; only errors if length is between 4',
    'http://oaa-accessibility.org/wcag20/rule/38/',
    'Link text should be as least four 4 characters long'
  ].join('\n')
};

module.exports.lint = function (element, opts) {
  //it's not a link if it doesn't have an href

  if (!element.attribs.href || !element.attribs.href.value) {
    return [];
  }

  var textElements = lodash.filter(element.children, (node) => { return node.type == 'text' });
  var content = textElements.map((textElement) => { return textElement.data }).join('').trim();
  length = content.length
  console.log('length'+length)
  return length < 4
    ? new Issue('WC38', element.openLineCol, { 'content': content, 'length': length })
    : [];
};
<commit_msg>removed debug log<commit_after>var Issue = require('../issue');
var lodash = require('lodash');

module.exports = {
  name: 'wcag-rule-38',
  on: ['tag'],
  filter: ['a'],
  desc: [
    'a rule from WCAG',
    'only triggers if the link has a link; only errors if length is between 4',
    'http://oaa-accessibility.org/wcag20/rule/38/',
    'Link text should be as least four 4 characters long'
  ].join('\n')
};

module.exports.lint = function (element, opts) {
  //it's not a link if it doesn't have an href

  if (!element.attribs.href || !element.attribs.href.value) {
    return [];
  }

  var textElements = lodash.filter(element.children, (node) => { return node.type == 'text' });
  var content = textElements.map((textElement) => { return textElement.data }).join('').trim();
  length = content.length
  return length < 4
    ? new Issue('WC38', element.openLineCol, { 'content': content, 'length': length })
    : [];
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDom from 'react-dom';

class App extends Component {
    constructor() {
        super();
        this.state = { val: 0 }
        this.update = this.update.bind(this)
    }
    update() {
        this.setState({ val: this.state.val + 1 });
    }
    componentWillMount() {
        console.log("componentWillMount");
    }
    render() {
        console.log("render");
        return <button onClick={this.update}>{ this.state.val }</button>
    }
    componentDidMount() {
        console.log("componentDidMount");
    }
    componentWillUnmount() {
        console.log("componentWillUnmount");
    }
}

class Wrapper extends Component {
    mount() {
        ReactDom.render(<App/>, document.getElementById("a"))
    }
    unmount() {
        ReactDom.unmountComponentAtNode(document.getElementById("a"))
    }
    render() {
        return (

                <button onClick={this.mount.bind(this) }>Mount</button>
                <button onClick={this.unmount.bind(this) }>Unmount</button>

        )
    }
}

export default Wrapper;
<commit_msg>Component cleanup<commit_after>import React, { Component } from 'react';
import ReactDom from 'react-dom';

class App extends Component {
    constructor() {
        super();
        this.state = { val: 0 }
        this.update = this.update.bind(this)
    }
    update() {
        this.setState({ val: this.state.val + 1 });
    }
    componentWillMount() {
        console.log("componentWillMount");
        this.setState({m:2});
    }
    render() {
        console.log("render");
        return <button onClick={this.update}>{ this.state.val * this.state.m }</button>
    }
    componentDidMount() {
        console.log("componentDidMount");
        //console.log(ReactDom.findDOMNode(this));
        this.inc = setInterval(this.update, 500);
    }
    componentWillUnmount() {
        console.log("componentWillUnmount");
        clearInterval(this.inc);
    }
}

class Wrapper extends Component {
    mount() {
        ReactDom.render(<App/>, document.getElementById("a"))
    }
    unmount() {
        ReactDom.unmountComponentAtNode(document.getElementById("a"))
    }
    render() {
        return (

                <button onClick={this.mount.bind(this) }>Mount</button>
                <button onClick={this.unmount.bind(this) }>Unmount</button>

        )
    }
}

export default Wrapper;
<|endoftext|>