<commit_before>define([
    "backbone",
    "handlebars",
    "data_list/DataList",
    "data_list/DataListEditView",
    "datum/Datums",
    "datum/DatumFields",
    "datum/Session",
    "libs/Utils"
], function(
    Backbone,
    Handlebars,
    DataList,
    DataListEditView,
    Datums,
    DatumFields,
    Session
) {
  var Import = Backbone.Model.extend(

  /** @lends Import.prototype */
  {
    /**
     * @class The import class helps import csv, xml and raw text data into a corpus, or create a new corpus.
     *
     * @property {FileList} files These are the file(s) that were dragged in.
     * @property {String} corpusname This is the corpusid where the data should be imported
     * @property {DatumFields} fields The fields array contains titles of the data columns.
     * @property {DataList} dataList the datalist imported, to hold the data before it is saved.
     * @property {Event} event The drag/drop event.
     *
     * @description The initialize serves to bind import to all drag and drop events.
     *
     * @extends Backbone.Model
     * @constructs
     */
    initialize : function() {
      this.set("corpusname", window.app.get("corpus").get("corpusname"));
      if(this.get("datumFields") == undefined){
        this.set("datumFields",window.app.get("corpus").get("datumFields").clone());
      }
    },

    // This is an list of attributes and their default values
    defaults : {
      status : "",
      fileDetails : "",
      corpusname : "",
      datumArray : [],
//      rawText: "",
//      asCSV : "", //leave undefined
//      asXML : "",
//      asDatumFields : "";
      files : [],
    },

    // Internal models: used by the parse function
    model : {
      dataList : DataList,
      fields : DatumFields,
      session : Session
    },

    /**
     * Describe the validation here.
     *
     * @param {Object} attributes The set of attributes to validate.
     *
     * @returns {String} The validation error, if there is one. Otherwise, doesn't
     * return anything.
     */
    validate : function(attributes) {
    },
    /**
     * This function tries to guess if you have \n or \r as line endings
     * and then tries to determine if you have "surounding your text".
     *
     * CSV is a common export format for Filemaker, Microsoft Excel and
     * OpenOffice Spreadsheets, and could be a good format to export
     * from these sources and import into iField.
     *
     * @param text
     */
    importCSV : function(text) {
      var rows = text.split("\n");
      if(rows.length < 3){
        rows = text.split("\r");
        this.set("status", this.get("status","Detected a \r line ending."));
      }
      var hasQuotes = false;
      //If it looks like it already has quotes:
      if( rows[0].split('","').length > 2 && rows[5].split('","').length > 2){
        hasQuotes = true;
        this.set("status", this.get("status","Detected text was already surrounded in quotes."));
      }
      for(l in rows){
        if(hasQuotes){
          rows[l] = rows[l].trim().replace(/^"/,"").replace(/"$/,"").split('","');
//          var withoutQuotes = [];
//          _.each(rows[l],function(d){
//            withoutQuotes.push(d.replace(/"/g,""));
//          });
//          rows[l] = withoutQuotes;
        }else{
          rows[l] = this.parseLineCSV(rows[l]);
        }
      }

      this.set("asCSV", rows);
    },

    /**
     * http://purbayubudi.wordpress.com/2008/11/09/csv-parser-using-javascript/
     * // -- CSV PARSER --
      // author  : Purbayu, 30Sep2008
      // email   : purbayubudi@gmail.com
      //
      // description :
      //  This jscript code describes how to load csv file and parse it into fields.
      //  Additionally, a function to display html table as result is added.
      //
      // disclamer:
      //  To use this code freely, you must put author's name in it.
     */
    parseLineCSV : function(lineCSV) {
      // parse csv line by line into array
      var CSV = new Array();

      // Insert space before character ",". This is to anticipate
      // 'split' in IE
      // try this:
      //
      // var a=",,,a,,b,,c,,,,d";
      // a=a.split(/\,/g);
      // document.write(a.length);
      //
      // You will see unexpected result!
      //
      lineCSV = lineCSV.replace(/,/g, " ,");

      lineCSV = lineCSV.split(/,/g);

      // This is continuing of 'split' issue in IE
      // remove all trailing space in each field
      for ( var i = 0; i < lineCSV.length; i++) {
        lineCSV[i] = lineCSV[i].replace(/\s*$/g, "");
      }

      lineCSV[lineCSV.length - 1] = lineCSV[lineCSV.length - 1]
      .replace(/^\s*|\s*$/g, "");
      var fstart = -1;

      for ( var i = 0; i < lineCSV.length; i++) {
        if (lineCSV[i].match(/"$/)) {
          if (fstart >= 0) {
            for ( var j = fstart + 1; j <= i; j++) {
              lineCSV[fstart] = lineCSV[fstart] + "," + lineCSV[j];
              lineCSV[j] = "-DELETED-";
            }
            fstart = -1;
          }
        }
        fstart = (lineCSV[i].match(/^"/)) ? i : fstart;
      }

      var j = 0;

      for ( var i = 0; i < lineCSV.length; i++) {
        if (lineCSV[i] != "-DELETED-") {
          CSV[j] = lineCSV[i];
          CSV[j] = CSV[j].replace(/^\s*|\s*$/g, ""); // remove leading & trailing
          // space
          CSV[j] = CSV[j].replace(/^"|"$/g, ""); // remove " on the beginning
          // and end
          CSV[j] = CSV[j].replace(/""/g, '"'); // replace "" with "
          j++;
        }
      }

      return CSV;
    },
    importXML : function(xml) {
    },
    /**
     * This function accepts text which uses \t tabs between columns. If
     * you have your data in ELAN or in Microsoft Excel or OpenOffice
     * spreadsheets, this will most likely be a good format to export
     * your data, and import into iField. This function is triggered if
     * your file has more than 100 tabs in it, iField guesses that it
     * should try this function.
     *
     * @param tabbed
     */
    importTabbed : function(text) {
      var rows = text.split("\n");
      if(rows.length < 3){
        rows = text.split("\r");
        this.set("status", this.get("status","Detected a \n line ending."));
      }
      for(l in rows){
        rows[l] = rows[l].split("\t");
      }

      this.set("asCSV", rows);
    },
    /**
     * This function accepts text using double spaces to indicate
     * separate datum. Each line in the block is treated as a column in
     * the table.
     *
     * If you have your data in Microsoft word or OpenOffice or plain
     * text, then this will be the easiest format for you to import your
     * data in.
     *
     * @param text
     */
    importText : function(text) {
      var rows = text.split("\n\n");
      var macLineEndings = false;
      if(rows.length < 3){
        rows = text.split("\r\r");
        macLineEndings = true;
        this.set("status", this.get("status","Detected a MAC line ending."));
      }
      for(l in rows){
        if(macLineEndings){
          rows[l] = rows[l].replace(/  +/g," ").split("\r");
        }else{
          rows[l] = rows[l].replace(/  +/g," ").split("\n");
        }
      }
      this.set("asCSV", rows);
    },
    readFiles : function(){
      var filedetails = [];
      var files = this.get("files");
      Utils.debug(files);
      for ( var i = 0, f; f = files[i]; i++) {
        filedetails.push( escape(f.name), f.type
            || ' n/a', ' - ', f.size, ' bytes, last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString()
                : ' n/a');

        this.readFileIntoRawText(i, function(){
          Utils.debug("Finished reading in the raw text file.")
        });
//        this.set("asCSV", this.importCSV(f.getBytes()));
//      this.set("asXML", this.importCSV(f.getBytes()));

      }

      var status = this.get("status");
      this.set("fileDetails", filedetails.join('') );
      status = status + filedetails.join('');
      this.set("status", status);
      if (this.get("dataList") == undefined) {
        // Create a new DataList
        this.set("dataList", new DataList({
          title : "Data from "+files[0].name,
          description : "This is the data list which would result from the import of these files."
            + this.get("fileDetails"),
          corpusname: this.get("corpusname")
        }));

        // Create a new DataListEditView
        this.dataListView = new DataListEditView({
          model : this.get("dataList"),
          datumCollection : new Datums()
        });
        this.dataListView.format = "import";
      }

      // Render the DataList
      this.dataListView.render();
    },
    readFileIntoRawText : function(index, callback){
      var self = this;
      this.readBlob(this.get("files")[index], function(){
        self.guessFormatAndImport(0, callback);
      });
    },
    /**
     * This function attempts to guess the format of the file, and calls the appropriate import handler.
     */
    guessFormatAndImport : function(fileIndex, callback){
      var self = this;
      if(fileIndex == null){
        fileIndex = 0;
      }
      //if the user is just typing, try raw text
      if(!self.get("files")[fileIndex]){
        self.importText(self.get("rawText"), callback);
        return;
      }
      if(self.get("files")[fileIndex].name.split('.').pop() == "csv"){
        self.importCSV(self.get("rawText"), callback);
      }else if(self.get("files")[fileIndex].name.split('.').pop() == "txt"){
        //If there are more than 100 tabs in the file, try tabbed.
        if(self.get("rawText").split("\t").length > 100){
          self.importTabbed(self.get("rawText"), callback);
        }else{
          self.importText(self.get("rawText"), callback);
        }
      }else if(self.get("files")[fileIndex].name.split('.').pop() == "eaf"){
        self.importXML(self.get("rawText"), callback);
      }
    },
    readBlob : function (file, callback, opt_startByte, opt_stopByte) {
      //console.log(this);
      var start = parseInt(opt_startByte) || 0;
      var stop = parseInt(opt_stopByte) || file.size - 1;
      var reader = new FileReader();

      var self = this;
      // If we use onloadend, we need to check the readyState.
      reader.onloadend = function(evt) {
        if (evt.target.readyState == FileReader.DONE) { // DONE == 2
          self.set("rawText", evt.target.result);
          if(typeof callback == "function"){
            callback();
          }
        }
      };
      var blob = '';
      if (file.webkitSlice) {
        blob = file.webkitSlice(start, stop + 1);
      } else if (file.mozSlice) {
        blob = file.mozSlice(start, stop + 1);
      }
      reader.readAsBinaryString(blob);
//      reader.readAsText(file);
    }
  });

  return Import;
});<commit_msg>using statistics to guess the appropraite import type from filenames and text contents,  and calling the appropriate import handler<commit_after>define([
    "backbone",
    "handlebars",
    "data_list/DataList",
    "data_list/DataListEditView",
    "datum/Datums",
    "datum/DatumFields",
    "datum/Session",
    "libs/Utils"
], function(
    Backbone,
    Handlebars,
    DataList,
    DataListEditView,
    Datums,
    DatumFields,
    Session
) {
  var Import = Backbone.Model.extend(

  /** @lends Import.prototype */
  {
    /**
     * @class The import class helps import csv, xml and raw text data into a corpus, or create a new corpus.
     *
     * @property {FileList} files These are the file(s) that were dragged in.
     * @property {String} corpusname This is the corpusid where the data should be imported
     * @property {DatumFields} fields The fields array contains titles of the data columns.
     * @property {DataList} dataList the datalist imported, to hold the data before it is saved.
     * @property {Event} event The drag/drop event.
     *
     * @description The initialize serves to bind import to all drag and drop events.
     *
     * @extends Backbone.Model
     * @constructs
     */
    initialize : function() {
      this.set("corpusname", window.app.get("corpus").get("corpusname"));
      if(this.get("datumFields") == undefined){
        this.set("datumFields",window.app.get("corpus").get("datumFields").clone());
      }
    },

    // This is an list of attributes and their default values
    defaults : {
      status : "",
      fileDetails : "",
      corpusname : "",
      datumArray : [],
//      rawText: "",
//      asCSV : "", //leave undefined
//      asXML : "",
//      asDatumFields : "";
      files : [],
    },

    // Internal models: used by the parse function
    model : {
      dataList : DataList,
      fields : DatumFields,
      session : Session
    },

    /**
     * Describe the validation here.
     *
     * @param {Object} attributes The set of attributes to validate.
     *
     * @returns {String} The validation error, if there is one. Otherwise, doesn't
     * return anything.
     */
    validate : function(attributes) {
    },
    /**
     * This function tries to guess if you have \n or \r as line endings
     * and then tries to determine if you have "surounding your text".
     *
     * CSV is a common export format for Filemaker, Microsoft Excel and
     * OpenOffice Spreadsheets, and could be a good format to export
     * from these sources and import into iField.
     *
     * @param text
     */
    importCSV : function(text) {
      var rows = text.split("\n");
      if(rows.length < 3){
        rows = text.split("\r");
        this.set("status", this.get("status","Detected a \r line ending."));
      }
      var hasQuotes = false;
      //If it looks like it already has quotes:
      if( rows[0].split('","').length > 2 && rows[5].split('","').length > 2){
        hasQuotes = true;
        this.set("status", this.get("status","Detected text was already surrounded in quotes."));
      }
      for(l in rows){
        if(hasQuotes){
          rows[l] = rows[l].trim().replace(/^"/,"").replace(/"$/,"").split('","');
//          var withoutQuotes = [];
//          _.each(rows[l],function(d){
//            withoutQuotes.push(d.replace(/"/g,""));
//          });
//          rows[l] = withoutQuotes;
        }else{
          rows[l] = this.parseLineCSV(rows[l]);
        }
      }

      this.set("asCSV", rows);
    },

    /**
     * http://purbayubudi.wordpress.com/2008/11/09/csv-parser-using-javascript/
     * // -- CSV PARSER --
      // author  : Purbayu, 30Sep2008
      // email   : purbayubudi@gmail.com
      //
      // description :
      //  This jscript code describes how to load csv file and parse it into fields.
      //  Additionally, a function to display html table as result is added.
      //
      // disclamer:
      //  To use this code freely, you must put author's name in it.
     */
    parseLineCSV : function(lineCSV) {
      // parse csv line by line into array
      var CSV = new Array();

      // Insert space before character ",". This is to anticipate
      // 'split' in IE
      // try this:
      //
      // var a=",,,a,,b,,c,,,,d";
      // a=a.split(/\,/g);
      // document.write(a.length);
      //
      // You will see unexpected result!
      //
      lineCSV = lineCSV.replace(/,/g, " ,");

      lineCSV = lineCSV.split(/,/g);

      // This is continuing of 'split' issue in IE
      // remove all trailing space in each field
      for ( var i = 0; i < lineCSV.length; i++) {
        lineCSV[i] = lineCSV[i].replace(/\s*$/g, "");
      }

      lineCSV[lineCSV.length - 1] = lineCSV[lineCSV.length - 1]
      .replace(/^\s*|\s*$/g, "");
      var fstart = -1;

      for ( var i = 0; i < lineCSV.length; i++) {
        if (lineCSV[i].match(/"$/)) {
          if (fstart >= 0) {
            for ( var j = fstart + 1; j <= i; j++) {
              lineCSV[fstart] = lineCSV[fstart] + "," + lineCSV[j];
              lineCSV[j] = "-DELETED-";
            }
            fstart = -1;
          }
        }
        fstart = (lineCSV[i].match(/^"/)) ? i : fstart;
      }

      var j = 0;

      for ( var i = 0; i < lineCSV.length; i++) {
        if (lineCSV[i] != "-DELETED-") {
          CSV[j] = lineCSV[i];
          CSV[j] = CSV[j].replace(/^\s*|\s*$/g, ""); // remove leading & trailing
          // space
          CSV[j] = CSV[j].replace(/^"|"$/g, ""); // remove " on the beginning
          // and end
          CSV[j] = CSV[j].replace(/""/g, '"'); // replace "" with "
          j++;
        }
      }

      return CSV;
    },
    importXML : function(xml) {
      alert("The app thinks this might be a XML file, but we haven't implemented this kind of import yet.");
    },
    /**
     * This function accepts text which uses \t tabs between columns. If
     * you have your data in ELAN or in Microsoft Excel or OpenOffice
     * spreadsheets, this will most likely be a good format to export
     * your data, and import into iField. This function is triggered if
     * your file has more than 100 tabs in it, iField guesses that it
     * should try this function.
     *
     * @param tabbed
     */
    importTabbed : function(text) {
      var rows = text.split("\n");
      if(rows.length < 3){
        rows = text.split("\r");
        this.set("status", this.get("status","Detected a \n line ending."));
      }
      for(l in rows){
        rows[l] = rows[l].split("\t");
      }

      this.set("asCSV", rows);
    },
    importToolbox : function(text){
      alert("The app thinks this might be a ToolBox file, but we haven't implemented this kind of import yet.");
    },
    importTextGrid : function(text){
      alert("The app thinks this might be a Praat TextGrid file, but we haven't implemented this kind of import yet.");
    },
    importLatex : function(text){
      alert("The app thinks this might be a LaTeX file, but we haven't implemented this kind of import yet.");
    },
    /**
     * This function accepts text using double spaces to indicate
     * separate datum. Each line in the block is treated as a column in
     * the table.
     *
     * If you have your data in Microsoft word or OpenOffice or plain
     * text, then this will be the easiest format for you to import your
     * data in.
     *
     * @param text
     */
    importText : function(text) {
      var rows = text.split("\n\n");
      var macLineEndings = false;
      if(rows.length < 3){
        rows = text.split("\r\r");
        macLineEndings = true;
        this.set("status", this.get("status","Detected a MAC line ending."));
      }
      for(l in rows){
        if(macLineEndings){
          rows[l] = rows[l].replace(/  +/g," ").split("\r");
        }else{
          rows[l] = rows[l].replace(/  +/g," ").split("\n");
        }
      }
      this.set("asCSV", rows);
    },
    readFiles : function(){
      var filedetails = [];
      var files = this.get("files");
      Utils.debug(files);
      for ( var i = 0, f; f = files[i]; i++) {
        filedetails.push( escape(f.name), f.type
            || ' n/a', ' - ', f.size, ' bytes, last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString()
                : ' n/a');

        this.readFileIntoRawText(i, function(){
          Utils.debug("Finished reading in the raw text file.")
        });
//        this.set("asCSV", this.importCSV(f.getBytes()));
//      this.set("asXML", this.importCSV(f.getBytes()));

      }

      var status = this.get("status");
      this.set("fileDetails", filedetails.join('') );
      status = status + filedetails.join('');
      this.set("status", status);
      if (this.get("dataList") == undefined) {
        // Create a new DataList
        this.set("dataList", new DataList({
          title : "Data from "+files[0].name,
          description : "This is the data list which would result from the import of these files."
            + this.get("fileDetails"),
          corpusname: this.get("corpusname")
        }));

        // Create a new DataListEditView
        this.dataListView = new DataListEditView({
          model : this.get("dataList"),
          datumCollection : new Datums()
        });
        this.dataListView.format = "import";
      }

      // Render the DataList
      this.dataListView.render();
    },
    readFileIntoRawText : function(index, callback){
      var self = this;
      this.readBlob(this.get("files")[index], function(){
        self.guessFormatAndImport(0, callback);
      });
    },
    /**
     * This function attempts to guess the format of the file/textarea, and calls the appropriate import handler.
     */
    guessFormatAndImport : function(fileIndex, callback){
      var self = this;
      if(fileIndex == null){
        fileIndex = 0;
      }
      var importType = {
        csv: { confidence: 0, importFunction : this.importCSV }
        ,tabbed: { confidence: 0, importFunction : this.importTabbed }
        ,handout: { confidence: 0, importFunction : this.importText }
        ,xml: { confidence: 0, importFunction : this.importXML }
        ,toolbox: { confidence: 0, importFunction : this.importToolbox }
        ,elanXML: { confidence: 0, importFunction : this.importXML }
        ,praatTextgrid: { confidence: 0, importFunction : this.importTextGrid }
        ,latex: { confidence: 0, importFunction : this.importLatex }
      };

      //if the user is just typing, try raw text
      if(self.get("files")[fileIndex]){
        var fileExtension = self.get("files")[fileIndex].name.split('.').pop().toLowerCase();
        if(fileExtension == "csv"){
          importType.csv.confidence++;
        }else if(fileExtension == "txt"){
          //If there are more than 100 tabs in the file, try tabbed.
          if(self.get("rawText").split("\t").length > 100){
            importType.tabbed.confidence++;
          }else{
            importType.handout.confidence++;
          }
        }else if(fileExtension == "eaf"){
          importType.elanXML.confidence++;
        }else if(fileExtension == "xml"){
          importType.xml.confidence++;
        }else if(fileExtension == "sf"){
          importType.toolbox.confidence++;
        }else if(fileExtension == "tex"){
          importType.latex.confidence++;
        }else if(fileExtension == "textgrid"){
          importType.praatTextgrid.confidence++;
        }
      }
      var mostLikelyImport = _.max(importType, function(obj) { return obj.confidence; });
      mostLikelyImport.importFunction.apply(self.get("rawText"), callback);
    },
    readBlob : function (file, callback, opt_startByte, opt_stopByte) {
      //console.log(this);
      var start = parseInt(opt_startByte) || 0;
      var stop = parseInt(opt_stopByte) || file.size - 1;
      var reader = new FileReader();

      var self = this;
      // If we use onloadend, we need to check the readyState.
      reader.onloadend = function(evt) {
        if (evt.target.readyState == FileReader.DONE) { // DONE == 2
          self.set("rawText", evt.target.result);
          if(typeof callback == "function"){
            callback();
          }
        }
      };
      var blob = '';
      if (file.webkitSlice) {
        blob = file.webkitSlice(start, stop + 1);
      } else if (file.mozSlice) {
        blob = file.mozSlice(start, stop + 1);
      }
      reader.readAsBinaryString(blob);
//      reader.readAsText(file);
    }
  });

  return Import;
});<|endoftext|>


<commit_before>openerp.t4clinical_ui = function (instance) {

    var QWeb = instance.web.qweb;
    var timing, timing2, timing3;
    var refresh_placement = false;
    var refresh_active_poc = false;
    var _t = instance.web._t;

    instance.t4clinical_ui.Button = instance.web.list.Column.extend({
        format: function (row_data, options) {
            options = options || {};
            var attrs = {};
            if (options.process_modifiers !== false) {
                attrs = this.modifiers_for(row_data);
            }
            if (attrs.invisible) { return ''; }
            if (this.widget == 'act_button'){
                return QWeb.render('t4.ListView.row.act_button', {
                    widget: this,
                    prefix: instance.session.prefix,
                    active: row_data.active.value,
                    inactive: !row_data.active.value,
                    disabled: attrs.readonly
                        || isNaN(row_data.id.value)
                        || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
                })
            }
            else{
                return QWeb.render('t4.ListView.row.button', {
                    widget: this,
                    prefix: instance.session.prefix,
                    disabled: attrs.readonly
                        || isNaN(row_data.id.value)
                        || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
                })
            }
        }
    });

    instance.web.list.columns.add('button', 'instance.t4clinical_ui.Button');

    instance.web.UserMenu.include({
        on_menu_help: function() {
            window.open('http://www.tactix4.net', '_blank');
        },
        do_update: function(){
            var self = this;
            var fct = function() {
                var $avatar = self.$el.find('.oe_topbar_avatar');
                $avatar.attr('src', $avatar.data('default-src'));
                if (!self.session.uid)
                    return;
                var func = new instance.web.Model("res.users").get_func("read");
                return self.alive(func(self.session.uid, ["name", "company_id"])).then(function(res) {
                    var topbar_name = res.name;
                    if(instance.session.debug)
                        topbar_name = _.str.sprintf("%s (%s)", topbar_name, instance.session.db);
                    if(res.company_id[0] > 1)
                        topbar_name = _.str.sprintf("%s (%s)", topbar_name, res.company_id[1]);
                    self.$el.find('.oe_topbar_name').text(topbar_name);
                    if (!instance.session.debug) {
                        topbar_name = _.str.sprintf("%s (%s)", topbar_name, instance.session.db);
                    }
                    var avatar_src = self.session.url('/web/binary/image', {model:'res.users', field: 'image_small', id: self.session.uid});
                    $avatar.attr('src', avatar_src);
                });
            };
            this.update_promise = this.update_promise.then(fct, fct);
        },
    });

    instance.web.ListView.include({
        init: function(parent, dataset, view_id, options) {

            if (options.action){
                if (options.action.name == "Patient Placements" || options.action.name == "Wardboard" || options.action.name == "Active Points of Care" || options.action.name == "Inactive Points of Care"){
                    options.selectable = false;
                };
                if (options.action.name == "Wardboard"){
                    if (typeof(timing) != 'undefined'){
                        clearInterval(timing);
                    }
                    timing = window.setInterval(function(){
                        var button =  $("a:contains('Wardboard')");
                        if ($(".ui-dialog").length == 0 && button.parent('li').hasClass('oe_active') && $(".oe_view_manager_view_list").css('display') != 'none'){
                            button.click();
                        }
                    }, 300000);
                }
                else if (options.action.name == "Patient Placements"){
                    if (typeof(timing2) != 'undefined'){
                        clearInterval(timing2);
                    }
                    timing2 = window.setInterval(function(){
                        var button =  $("a:contains('Patient Placements')");
                        if ($(".ui-dialog").length == 0 && $(".oe_view_manager_view_list").css('display') != 'none'){
                            if (refresh_placement){
                                button.click();
                                refresh_placement = false;
                            }
                        }
                    }, 10);
                }
                else if (options.action.name == "Active Points of Care" || options.action.name == "Inactive Points of Care"){
                    if (typeof(timing3) != 'undefined'){
                        clearInterval(timing3);
                    }
                    timing3 = window.setInterval(function(){
                        if (options.action.name == "Active Points of Care"){
                            var button =  $("a:contains('Active Points of Care')");
                        } else {
                            var button =  $("a:contains('Inactive Points of Care')");
                        }
                        if ($(".ui-dialog").length == 0 && $(".oe_view_manager_view_list").css('display') != 'none'){
                            if (refresh_active_poc){
                                button.click();
                                refresh_active_poc = false;
                            }
                        }
                    }, 10);
                }
                else{
                    if (typeof(timing) != 'undefined'){
                        clearInterval(timing);
                    }
                    if (typeof(timing2) != 'undefined'){
                        clearInterval(timing2);
                    }
                    if (typeof(timing3) != 'undefined'){
                        clearInterval(timing3);
                    }
                }
            };
            this._super.apply(this, [parent, dataset, view_id, options]);

        },

        select_record: function (index, view) {
            view = view || index == null ? 'form' : 'form';
            this.dataset.index = index;
            if (this.fields_view.name != "T4 Clinical patient placement activity Tree View"){
                _.delay(_.bind(function () {
                    this.do_switch_view(view);
                }, this));
            }
        },

        do_button_action: function (name, id, callback) {
            this.handle_button(name, id, callback);
            if (name == "activate_deactivate"){
                refresh_active_poc = true;
            }
        },

    });

    instance.t4clinical_ui.T4Many2One = instance.web.form.FieldMany2One.extend({
        get_search_result: function(search_val) {
            var self = this;

            var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
            var blacklist = this.get_search_blacklist();
            this.last_query = search_val;

            return this.orderer.add(dataset.name_search(
                    search_val, new instance.web.CompoundDomain(self.build_domain(), [["id", "not in", blacklist]]),
                    'ilike', this.limit + 1, self.build_context())).then(function(data) {
                self.last_search = data;
                // possible selections for the m2o
                var values = _.map(data, function(x) {
                    x[1] = x[1].split("\n")[0];
                    return {
                        label: _.str.escapeHTML(x[1]),
                        value: x[1],
                        name: x[1],
                        id: x[0],
                    };
                });

                // search more... if more results that max
                if (values.length > self.limit) {
                    values = values.slice(0, self.limit);
                    values.push({
                        label: _t("Search More..."),
                        action: function() {
                            dataset.name_search(search_val, self.build_domain(), 'ilike', false).done(function(data) {
                                self._search_create_popup("search", data);
                            });
                        },
                        classname: 'oe_m2o_dropdown_option'
                    });
                }

                return values;
            });
        }
    });

    instance.web.form.widgets.add('t4_many2one', 'instance.t4clinical_ui.T4Many2One');

    instance.t4clinical_ui.GenderWidget = instance.web.list.Column.extend({
        _format: function (row_data, options) {
            if (row_data.sex.value == 'M'){
                return QWeb.render('t4_maleCell', {
                    'widget': this,
                    'prefix': instance.session.prefix,
                });
            } else if (row_data.sex.value == 'F'){
                return QWeb.render('t4_femaleCell', {
                    'widget': this,
                    'prefix': instance.session.prefix,
                });
            } else {
                return 'Not Given';
            };
        },
    });

    instance.web.list.columns.add('field.t4_gender', 'instance.t4clinical_ui.GenderWidget');

    instance.t4clinical_ui.WidgetButton = instance.web.form.WidgetButton.extend({
        on_click: function() {
            var self = this;
            this.force_disabled = true;
            this.check_disable();
            this.execute_action().always(function() {
                self.force_disabled = false;
                self.check_disable();
            });
            if (this.string == "Confirm Placement"){
                refresh_placement = true;
                console.log(this);
            }
        },
    });
    instance.web.form.tags.add('button', 'instance.t4clinical_ui.WidgetButton');
}<commit_msg>[FIX] TASK 882 883 - View not refreshing anymore after the exception pop up showed up.<commit_after>openerp.t4clinical_ui = function (instance) {

    var QWeb = instance.web.qweb;
    var timing, timing2, timing3;
    var refresh_placement = false;
    var refresh_active_poc = false;
    var _t = instance.web._t;

    instance.t4clinical_ui.Button = instance.web.list.Column.extend({
        format: function (row_data, options) {
            options = options || {};
            var attrs = {};
            if (options.process_modifiers !== false) {
                attrs = this.modifiers_for(row_data);
            }
            if (attrs.invisible) { return ''; }
            if (this.widget == 'act_button'){
                return QWeb.render('t4.ListView.row.act_button', {
                    widget: this,
                    prefix: instance.session.prefix,
                    active: row_data.active.value,
                    inactive: !row_data.active.value,
                    disabled: attrs.readonly
                        || isNaN(row_data.id.value)
                        || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
                })
            }
            else{
                return QWeb.render('t4.ListView.row.button', {
                    widget: this,
                    prefix: instance.session.prefix,
                    disabled: attrs.readonly
                        || isNaN(row_data.id.value)
                        || instance.web.BufferedDataSet.virtual_id_regex.test(row_data.id.value)
                })
            }
        }
    });

    instance.web.list.columns.add('button', 'instance.t4clinical_ui.Button');

    instance.web.UserMenu.include({
        on_menu_help: function() {
            window.open('http://www.tactix4.net', '_blank');
        },
        do_update: function(){
            var self = this;
            var fct = function() {
                var $avatar = self.$el.find('.oe_topbar_avatar');
                $avatar.attr('src', $avatar.data('default-src'));
                if (!self.session.uid)
                    return;
                var func = new instance.web.Model("res.users").get_func("read");
                return self.alive(func(self.session.uid, ["name", "company_id"])).then(function(res) {
                    var topbar_name = res.name;
                    if(instance.session.debug)
                        topbar_name = _.str.sprintf("%s (%s)", topbar_name, instance.session.db);
                    if(res.company_id[0] > 1)
                        topbar_name = _.str.sprintf("%s (%s)", topbar_name, res.company_id[1]);
                    self.$el.find('.oe_topbar_name').text(topbar_name);
                    if (!instance.session.debug) {
                        topbar_name = _.str.sprintf("%s (%s)", topbar_name, instance.session.db);
                    }
                    var avatar_src = self.session.url('/web/binary/image', {model:'res.users', field: 'image_small', id: self.session.uid});
                    $avatar.attr('src', avatar_src);
                });
            };
            this.update_promise = this.update_promise.then(fct, fct);
        },
    });

    instance.web.ListView.include({
        init: function(parent, dataset, view_id, options) {

            if (options.action){
                if (options.action.name == "Patient Placements" || options.action.name == "Wardboard" || options.action.name == "Active Points of Care" || options.action.name == "Inactive Points of Care"){
                    options.selectable = false;
                };
                if (options.action.name == "Wardboard"){
                    if (typeof(timing) != 'undefined'){
                        clearInterval(timing);
                    }
                    timing = window.setInterval(function(){
                        var button =  $("a:contains('Wardboard')");
                        if ($(".ui-dialog").length == 0 && button.parent('li').hasClass('oe_active') && $(".oe_view_manager_view_list").css('display') != 'none'){
                            button.click();
                        }
                    }, 300000);
                }
                else if (options.action.name == "Patient Placements"){
                    if (typeof(timing2) != 'undefined'){
                        clearInterval(timing2);
                    }
                    timing2 = window.setInterval(function(){
                        var button =  $("a:contains('Patient Placements')");
                        if ($(".ui-dialog").length == 0 && $(".oe_view_manager_view_list").css('display') != 'none'){
                            if (refresh_placement){
                                button.click();
                                refresh_placement = false;
                            }
                        }
                    }, 10);
                }
                else if (options.action.name == "Active Points of Care" || options.action.name == "Inactive Points of Care"){
                    if (typeof(timing3) != 'undefined'){
                        clearInterval(timing3);
                    }
                    timing3 = window.setInterval(function(){
                        if (options.action.name == "Active Points of Care"){
                            var button =  $("a:contains('Active Points of Care')");
                        } else {
                            var button =  $("a:contains('Inactive Points of Care')");
                        }
                        if (refresh_active_poc){
                            button.click();
                            refresh_active_poc = false;
                        }
                    }, 10);
                }
                else{
                    if (typeof(timing) != 'undefined'){
                        clearInterval(timing);
                    }
                    if (typeof(timing2) != 'undefined'){
                        clearInterval(timing2);
                    }
                    if (typeof(timing3) != 'undefined'){
                        clearInterval(timing3);
                    }
                }
            };
            this._super.apply(this, [parent, dataset, view_id, options]);

        },

        select_record: function (index, view) {
            view = view || index == null ? 'form' : 'form';
            this.dataset.index = index;
            if (this.fields_view.name != "T4 Clinical patient placement activity Tree View"){
                _.delay(_.bind(function () {
                    this.do_switch_view(view);
                }, this));
            }
        },

        do_button_action: function (name, id, callback) {
            this.handle_button(name, id, callback);
            if (name == "activate_deactivate"){
                refresh_active_poc = true;
            }
        },

    });

    instance.t4clinical_ui.T4Many2One = instance.web.form.FieldMany2One.extend({
        get_search_result: function(search_val) {
            var self = this;

            var dataset = new instance.web.DataSet(this, this.field.relation, self.build_context());
            var blacklist = this.get_search_blacklist();
            this.last_query = search_val;

            return this.orderer.add(dataset.name_search(
                    search_val, new instance.web.CompoundDomain(self.build_domain(), [["id", "not in", blacklist]]),
                    'ilike', this.limit + 1, self.build_context())).then(function(data) {
                self.last_search = data;
                // possible selections for the m2o
                var values = _.map(data, function(x) {
                    x[1] = x[1].split("\n")[0];
                    return {
                        label: _.str.escapeHTML(x[1]),
                        value: x[1],
                        name: x[1],
                        id: x[0],
                    };
                });

                // search more... if more results that max
                if (values.length > self.limit) {
                    values = values.slice(0, self.limit);
                    values.push({
                        label: _t("Search More..."),
                        action: function() {
                            dataset.name_search(search_val, self.build_domain(), 'ilike', false).done(function(data) {
                                self._search_create_popup("search", data);
                            });
                        },
                        classname: 'oe_m2o_dropdown_option'
                    });
                }

                return values;
            });
        }
    });

    instance.web.form.widgets.add('t4_many2one', 'instance.t4clinical_ui.T4Many2One');

    instance.t4clinical_ui.GenderWidget = instance.web.list.Column.extend({
        _format: function (row_data, options) {
            if (row_data.sex.value == 'M'){
                return QWeb.render('t4_maleCell', {
                    'widget': this,
                    'prefix': instance.session.prefix,
                });
            } else if (row_data.sex.value == 'F'){
                return QWeb.render('t4_femaleCell', {
                    'widget': this,
                    'prefix': instance.session.prefix,
                });
            } else {
                return 'Not Given';
            };
        },
    });

    instance.web.list.columns.add('field.t4_gender', 'instance.t4clinical_ui.GenderWidget');

    instance.t4clinical_ui.WidgetButton = instance.web.form.WidgetButton.extend({
        on_click: function() {
            var self = this;
            this.force_disabled = true;
            this.check_disable();
            this.execute_action().always(function() {
                self.force_disabled = false;
                self.check_disable();
            });
            if (this.string == "Confirm Placement"){
                refresh_placement = true;
                console.log(this);
            }
        },
    });
    instance.web.form.tags.add('button', 'instance.t4clinical_ui.WidgetButton');
}<|endoftext|>


<commit_before><commit_msg>remove stray file accidentally added to git repo<commit_after><|endoftext|>


<commit_before>var FavimExtension = {

	prefs: Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch),
	stringBundle: null,
	alertsService: Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService),
	currentElement: null,

	toolbarClick: function() {
		FavimExtension.isUserLogged(function(res) {
			if($.isEmptyObject(res)) {
				/* Пользователь не авторизован на favim.com */
				FavimExtension.alertsService.showAlertNotification("chrome://Favim/skin/icon32.png", "Ошибка", "Вы не авторизованы на Favim.com.", false);
			}
			else {
				/* Пользователь авторизован на Favim.com, загружаем все изображение со страницы */
				var content_body = $(content.document.body),
					images = null;

				$(content.document).scrollTop(0);

				FavimExtension.addFavimToPage(content_body);

				content_body.find('img').each(function(i, val) {
					if(val.naturalWidth < 215 || val.naturalHeight < 185) {
						return true;
					}
					FavimExtension.addImageToFavimBar(content_body, val, val.naturalWidth, val.naturalHeight);
				});

				content_body.find('*[src]').not('img').each(function(i, val) {
					var image = new Image();
					image.src = $(val).attr('src');

					if(image.width < 215 || image.height < 185) {
						return true;
					}
					FavimExtension.addImageToFavimBar(content_body, val, image.width, image.height);
				});

				if(content_body.find('.favim-image').length == 1) {
					var image = new Image();
					image.src = content_body.find('.favim-image > img').attr('src');

					content_body.find('.favim-image').css({
						'background': 'url('+ $(image).attr('src') + ')',
						'background-position': 'center top'
					});

					content_body.find('.favim-image, .favim-add').css({
						width: image.width / 2,
						height: image.height / 2
					});

					content_body.find('.favim-size').css({
						width: image.width / 2
					});

					content_body.find('.favim-add-heart').css('left', '40%');

					content_body.find('.favim-image > img').css('display', 'none');
				}

				content_body.find("#favim-save").css({
					'height': content_body[0].scrollHeight
				});

				content_body.find('.favim-close').on('click', function(e) {
					content_body.find('#favim-save').remove();
				});

				content_body.find(".favim-image").on('click', function(e) {
					FavimExtension.uploadImage($(this).children(':first'));
				});
			}
		});
	},
	onLoad: function() {
		if(FavimExtension.isFirstRun()) {
			FavimExtension.addIcon("nav-bar", "favim-button");
			FavimExtension.addIcon("addon-bar", "favim-button");
		}
		var contextMenu = document.getElementById("contentAreaContextMenu");
		if(contextMenu) {
			contextMenu.addEventListener('popupshowing', function(e) {
				var contextFavim = document.getElementById("contextFavim");
				if($(document.popupNode).prop('tagName').toLowerCase() != 'img') {
					contextFavim.hidden = true;
					return;
				}
				contextFavim.hidden = false;
			});
		}
	},
	isFirstRun: function() {
		var firstRun = FavimExtension.prefs.getBoolPref('extensions.favim.firstRun'),
			currentVersion = 1.0;
		if(firstRun) {
			FavimExtension.prefs.setBoolPref('extensions.favim.firstRun', false);
			FavimExtension.prefs.setCharPref('extensions.favim.installedVersion', currentVersion);
		}

		if(parseFloat(FavimExtension.prefs.getCharPref('extensions.favim.installedVersion')) < currentVersion) {
			FavimExtension.prefs.setCharPref('extensions.favim.installedVersion', currentVersion.toString());

			return true;
		}

		return firstRun;
	},
	addIcon: function(toolbarId, id) {
		if(!document.getElementById(id)) {
			var toolbar = document.getElementById(toolbarId);

			toolbar.insertItem(id, null);
			toolbar.setAttribute("currentset", toolbar.currentSet);

			document.persist(toolbar.id, "currentset");

			if(toolbarId == "addon-bar") {
				toolbar.collapsed = false;
			}
	    }
	},
	getOffsetElement: function(element) {
		var top = 0, left = 0
	    while(element) {
			top = top + parseFloat(element.offsetTop)
			left = left + parseFloat(element.offsetLeft)
			element = element.offsetParent
	    }

		return {
			top: Math.round(top),
			left: Math.round(left)
		}
	},
	isUserLogged: function(callback) {
		$.ajax({
			url: 'http://favim.com/ext/getuser.php',
			cache: false,
			dataType: "json",
			success: function(data) {
				callback(data);
			}
		});
	},
	uploadImage: function(element) {
		var popup = 'http://favim.com/ext/getpopup/',
			current_src = $(element).attr('src');
		if(content.document.domain == 'favim.ru' || content.document.domain == 'favim.com') {
			FavimExtension.alertsService.showAlertNotification("chrome://Favim/skin/icon32.png", "Ошибка", "Невозможно загрузить изображения с самого сайта Favim.com.", false);
			return false;
		}
		FavimExtension.isUserLogged(function(res) {
			if($.isEmptyObject(res)) {
				/* Пользователь не авторизован на favim.com */
				FavimExtension.alertsService.showAlertNotification("chrome://Favim/skin/icon32.png", "Ошибка", "Вы не авторизованы на Favim.com.", false);
			}
			else {
				if(!current_src.match(/^[a-zа-я\-\_0-9\.]+\.[a-z]+|^https?\:\/\//i) && current_src.length < 256) {
					current_src = 'http://' + content.document.domain + current_src;
				}

				let top = ($(content.window).height() / 2) - (380 / 2),
					left = ($(content.window).width() / 2) - (590 / 2);

				window.open(popup + '?media='+ encodeURIComponent(current_src), "Favin.com", "width=590, height=380, top="+ top + ", left="+ left);
			}
		});
	},
	contextSave: function(e) {
		/* Сохраняем изображение при клике в контекстном меню */
		FavimExtension.uploadImage($(document.popupNode));
	},
	URLIsInvalid: function(url) {
		return url.match(/.+\.(jpg|jpeg|png|gif)$/i) ? false : true;
	},
	addFavimDragMenu: function(doc) {
		if(!doc.find('.fw-main').length) {
			doc.append('\

\

\

favim.com
\

\
							Перетащите картинку\

\
							чтобы сохранить\

\

\

');

			doc.find(".fw-main").css({
				'top': $(content.window).height() / 2.5
			});

			doc.append('');
		}
	},
	addFavimToPage: function(doc) {
		doc.append('
\

\

\

\

\

\

');
	},
	addImageToFavimBar: function(content, image, width, height) {
		content.find('#favim-save .favim-body').append('\

\
				\

\

\
						'+ width + 'x' + height +'\

\

\

\

\

\
		');
	}

};

window.addEventListener("load", function load(e) {
	FavimExtension.onLoad();

	window.removeEventListener("load", load, false);

	if(gBrowser) {
	    gBrowser.addEventListener('DOMContentLoaded', function(event) {

	    	var doc = $(content.document.body),
	    		current_image = null;

	    	FavimExtension.addFavimDragMenu(doc);

	    	if(!doc.find("#favimImage").length) {
	    		doc.append('

')
	    	}
			doc.on('mouseover', "img", function(e) {
				if(content.document.domain == 'favim.ru' || content.document.domain == 'favim.com') {
					return false;
				}
				if(this.width < 215 || this.height < 185) {
					return false;
				}

				current_image = $(this);

				var offset = $(this).offset();
				doc.find("#favimImage").css({
					'left': offset.left + 10,
					'top': offset.top + 10,
					'display': 'block'
				});
			})
			doc.on('mouseout', "img", function(e) {
				if(doc.find("#favimImage")[0] === $(e.relatedTarget)[0]) {
					return false;
				}
				doc.find("#favimImage").css('display', 'none');
			});
			doc.unbind('click').on('click', "#favimImage", function(e) {
				$(this).css('display', 'none');

				FavimExtension.uploadImage(current_image);
			});

			/* drag & drop */

			doc.on('dragstart', function(e) {
				if($(e.target).is('img')) {
					doc.find(".fw-main").css('display', 'block');
					FavimExtension.currentElement = $(e.target);
				}
				else {
					var children = $(e.target).find('img');
					if(children.length) {
						doc.find(".fw-main").css('display', 'block');
						FavimExtension.currentElement = children;
					}
				}
			});
			doc.on('dragover', '.fw-main', function(e) {
				e.preventDefault();
			});
			doc.unbind('drop').on('drop', '.fw-main', function(e) {
				e.preventDefault();
				FavimExtension.uploadImage(FavimExtension.currentElement);
			});
			doc.on('dragend', function(e) {
				doc.find(".fw-main").css('display', 'none');
			});

			/* iframe */
			doc.find('iframe').load(function() {
				var iframe_body = $(this).contents().find('body');
		    	if(!$(this).contents().find("#favimImage").length) {
		    		iframe_body.append('

')
		    	}

				iframe_body.on('dragstart', function(e) {
					if($(e.target).is('img')) {
						doc.find(".fw-main").css('display', 'block');
						FavimExtension.currentElement = $(e.target);
					}
					else {
						var children = $(e.target).find('img');
						if(children.length) {
							doc.find(".fw-main").css('display', 'block');
							FavimExtension.currentElement = children;
						}
					}
				});
				iframe_body.on('dragend', function(e) {
					doc.find(".fw-main").css('display', 'none');
				});
				iframe_body.on('mouseover', "img", function(e) {
					if(content.document.domain == 'favim.ru' || content.document.domain == 'favim.com') {
						return false;
					}
					if(this.naturalWidth < 215 || this.naturalHeight < 185) {
						return false;
					}

					current_image = $(this);

					var offset = $(this).offset();
					iframe_body.find('#favimImage').css({
						'left': offset.left + 10,
						'top': offset.top + 10,
						'display': 'block'
					});
				})
				iframe_body.on('mouseout', "img", function(e) {
					if(iframe_body.find('#favimImage')[0] === $(e.relatedTarget)[0]) {
						return false;
					}
					iframe_body.find('#favimImage').css('display', 'none');
				});
				iframe_body.unbind('click').on('click', "#favimImage", function(e) {
					$(this).css('display', 'none');

					FavimExtension.uploadImage(current_image);
				});
			});
	    }, false);
	}
}, false);<commit_msg>- oops;<commit_after>var ProxyAddonBar = {

	proxyList: [],
	prefs: Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch),
	stringBundle: null,

	onLoad: function(str) {
		ProxyAddonBar.stringBundle = str;

		if(ProxyAddonBar.isFirstRun()) {
			/* icon */
			ProxyAddonBar.addIcon("nav-bar", "myextension-button");
			ProxyAddonBar.addIcon("addon-bar", "myextension-button");
			/* ip address */
			ProxyAddonBar.addIcon("nav-bar", "ip-address");
			ProxyAddonBar.addIcon("addon-bar", "ip-address");
		}
	},
	addIcon: function(toolbarId, id) {
		if(!document.getElementById(id)) {
			var toolbar = document.getElementById(toolbarId);

			toolbar.insertItem(id, null);
			toolbar.setAttribute("currentset", toolbar.currentSet);

			document.persist(toolbar.id, "currentset");

			if(toolbarId == "addon-bar") {
				toolbar.collapsed = false;
			}
	    }
	},
	activate: function() {
		ProxyAddonBar.reset();
		ProxyAddonBar.parseProxyList(function(ip_addr) {
			var rand_proxy = ProxyAddonBar.randomProxy(ip_addr);
			if(rand_proxy[3] == 'http') {
				ProxyAddonBar.connectTo(rand_proxy);
			}
			else {
				ProxyAddonBar.connectToSSL(rand_proxy);
			}

			document.getElementById('ip-address').children[0].value = ProxyAddonBar.getIPAddress();

			ProxyAddonBar.proxyList = ip_addr;

			ProxyAddonBar.addItemsToProxyList();
		});
	},
	reset: function() {
		ProxyAddonBar.resetConfig();
		document.getElementById('ip-address').children[0].style.color = '#12B300';
		document.getElementById('ip-address').children[0].value = ProxyAddonBar.stringBundle.getString('proxyIsDisabled');
	},
	ping: function() {
		ProxyAddonBar.pingLogic(function(times) {
			document.getElementById('ip-address').children[0].value = ProxyAddonBar.getIPAddress() || ProxyAddonBar.stringBundle.getString('proxyIsDisabled');
			document.getElementById('ip-address').children[0].style.color = (times < 8) ? '#12B300' : '#B30000';
		});
	},
	chooseProxy: function(event) {
		if(!event.currentTarget.className.length) {
			event.currentTarget.setAttribute('class', 'active');
		}
		else {
			event.currentTarget.removeAttribute('class');
		}
	},
	changeProxy: function() {
		ProxyAddonBar.resetConfig();

		var hbox = document.getElementById('proxy-list-box').getElementsByTagName('hbox');
		for(var i = 0; i < hbox.length; i++) {
			if(hbox[i].className.length) {
				var hbox_child = hbox[i].children[0],
					proxy_type = hbox[i].getElementsByClassName('proxy-type')[0].innerHTML.toLowerCase();

				if(proxy_type == 'http') {
					ProxyAddonBar.connectTo([hbox_child.value, hbox_child.getAttribute('data-port')]);
				}
				else {
					ProxyAddonBar.connectToSSL([hbox_child.value, hbox_child.getAttribute('data-port')]);
				}

				document.getElementById('ip-address').children[0].value = ProxyAddonBar.getIPAddress();
				break;
			}
		}
	},
	refresh: function() {
		ProxyAddonBar.reset();
		ProxyAddonBar.parseProxyList(function(ip_addr) {
			ProxyAddonBar.proxyList = ip_addr;
			ProxyAddonBar.addItemsToProxyList();
		});
	},
	getIPAddress: function() {
		return ProxyAddonBar.prefs.getCharPref('network.proxy.http');
	},
	resetConfig: function() {
		ProxyAddonBar.prefs.clearUserPref('network.proxy.http');
		ProxyAddonBar.prefs.clearUserPref('network.proxy.http_port');
		ProxyAddonBar.prefs.clearUserPref('network.proxy.type');

		ProxyAddonBar.prefs.clearUserPref('network.proxy.ssl');
		ProxyAddonBar.prefs.clearUserPref('network.proxy.ssl_port');
	},
	connectTo: function(addr) {
		ProxyAddonBar.prefs.setCharPref('network.proxy.http', addr[0]);
		ProxyAddonBar.prefs.setIntPref('network.proxy.http_port', addr[1]);
		ProxyAddonBar.prefs.setIntPref('network.proxy.type', 1);
	},
	connectToSSL: function(addr) {
		ProxyAddonBar.prefs.setCharPref('network.proxy.http', addr[0]);
		ProxyAddonBar.prefs.setIntPref('network.proxy.http_port', addr[1]);

		ProxyAddonBar.prefs.setCharPref('network.proxy.ssl', addr[0]);
		ProxyAddonBar.prefs.setIntPref('network.proxy.ssl_port', addr[1]);
		ProxyAddonBar.prefs.setIntPref('network.proxy.type', 1);
	},
	randomProxy: function(proxy) {
		return proxy[parseInt(Math.random() * proxy.length - 1)];
	},
	pingLogic: function(callback) {
		var req = new XMLHttpRequest(),
			win = window.open("chrome://FireX/content/loading.xul", "", "chrome");
			pinged = 0,
			isCompleted = false;

		win.onload = function() {
			win.document.getElementById('loading_description').value = ProxyAddonBar.stringBundle.getString('waitCheckSpeed');
		}

		var	interval = setInterval(function() {
			win.document.getElementById('loading_description').value = ProxyAddonBar.stringBundle.getString('doneSeconds') + ': ' + parseInt(8 - pinged) + ' ' + ProxyAddonBar.stringBundle.getString('seconds');

			if(pinged >= 8) {
				win.close();
				clearInterval(interval);

				isCompleted = true;

				callback(pinged);
				return false;
			}

			pinged++;

		}, 1000);

		req.open('GET', 'http://www.mozilla.org/', true);
		req.onreadystatechange = function() {
			if(req.readyState == 4) {
				win.close();
				clearInterval(interval);
				if(!isCompleted) {
					callback(pinged);
				}
			}
		}
		req.send(null);
	},
	addItemsToProxyList: function() {
		var no_addr = document.getElementById('no_addresses');
		if(no_addr) {
			document.getElementById('proxy-list-box').removeChild(no_addr);
		}

		var proxy_list = document.getElementById('proxy-list-box');

		while(proxy_list.firstChild) {
			proxy_list.removeChild(proxy_list.firstChild);
		}

		for(var i = 0; i < ProxyAddonBar.proxyList.length; i++) {
			ProxyAddonBar.addProxyItem(ProxyAddonBar.proxyList[i][0], ProxyAddonBar.proxyList[i][1], ProxyAddonBar.proxyList[i][2], ProxyAddonBar.proxyList[i][3]);
		}
	},
	addProxyItem: function(value, port, country, type) {
		var xulNS = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul',
			hbox = document.createElementNS(xulNS, 'hbox');
			element = document.createElementNS(xulNS, 'label'),
			el_country = document.createElementNS(xulNS, 'label'),
			el_type = document.createElementNS(xulNS, 'label');

		element.setAttribute('value', value);
		element.setAttribute('data-port', port);

		hbox.addEventListener('click', function(e) {
			ProxyAddonBar.chooseProxy(e);
		}, false);

		el_country.textContent = country;
		el_country.setAttribute('class', 'proxy-country');

		el_type.textContent = type.toUpperCase();
		el_type.setAttribute('class', 'proxy-type');

		document.getElementById('proxy-list-box').appendChild(hbox);
		hbox.appendChild(element);
		hbox.appendChild(el_type);
		hbox.appendChild(el_country);
	},
	parseProxyList: function(callback) {
		var req = new XMLHttpRequest();
		req.open('GET', 'http://proxylist.hidemyass.com/', true);

		var win = window.open("chrome://FireX/content/loading.xul", "", "chrome");

		req.onreadystatechange = function() {
			if(req.readyState == 4) {
				if(req.status == 200) {

					var response = req.responseText,
						parser = new DOMParser(),
						doc = parser.parseFromString(response, "text/html"),
						doc_table = doc.getElementById("listable"),
						doc_tr = doc_table.getElementsByTagName('tbody')[0].getElementsByTagName('tr'),
						ip_addr = [];

					for(var i = 0; i < doc_tr.length; i++) {
						var doc_td = [
								doc_tr[i].getElementsByTagName('td')[1],
								doc_tr[i].getElementsByTagName('td')[2],
								doc_tr[i].getElementsByTagName('td')[4],
								doc_tr[i].getElementsByTagName('td')[5],
								doc_tr[i].getElementsByTagName('td')[3],
								doc_tr[i].getElementsByTagName('td')[6],
							],
							span = doc_td[0].getElementsByTagName('span')[0],
							loopAddr = '',
							proxySpeed = doc_td[2].getElementsByClassName('progress-indicator')[0].children[0].style.width,
							connectionTime = doc_td[3].getElementsByClassName('progress-indicator')[0].children[0].style.width,
							country = doc_td[4].getElementsByTagName('span')[0].textContent,
							proxy_type = doc_td[5].innerHTML.toLowerCase();

						if(connectionTime < parseInt(connectionTime) || parseInt(proxySpeed) < 40) {
							continue;
						}

						if(proxy_type != 'http' && proxy_type != 'https') {
							continue;
						}

						var match = span.getElementsByTagName('style')[0].innerHTML.match(/([^\n|.]+display:(?!none))/g),
							allElements = span.childNodes;

						for(var b = 0; b < allElements.length; b++) {
							var this_span = allElements[b],
								isLoop = false;

							if(this_span.textContent.length && this_span.tagName == undefined) {
								loopAddr += (loopAddr.length) ? '.' + this_span.textContent : this_span.textContent;
								continue;
							}

							if(this_span.style.display == "none") {
								continue;
							}

							if(this_span.tagName.toLowerCase() == 'style') {
								continue;
							}

							if(this_span.className.length) {
								for(var r = 0; r < match.length; r++) {
									if(match[r].replace(/{.*/, '') == this_span.className) {
										isLoop = true;
										break;
									}
								}
							}

							if(!this_span.innerHTML.length || this_span.innerHTML === '.') {
								continue;
							}

							if(!this_span.className.match(/^[0-9]+$/) && !isLoop && !this_span.style.display) {
								continue;
							}

							loopAddr += (loopAddr.length) ? '.' + this_span.innerHTML : this_span.innerHTML;
						}

						ip_addr.push([
							loopAddr.replace(/\.{2,}/g, '.'), doc_td[1].innerHTML, country, proxy_type
						]);
					}

					win.close();

					callback(ip_addr);
				}
			}
		}
		req.send(null);
	},
	preventHide: function(e) {
	    e.preventDefault();
	},
	isFirstRun: function() {
		var firstRun = ProxyAddonBar.prefs.getBoolPref('extensions.firex.firstRun'),
			currentVersion = 3.3;
		if(firstRun) {
			ProxyAddonBar.prefs.setBoolPref('extensions.firex.firstRun', false);
			ProxyAddonBar.prefs.setCharPref('extensions.firex.installedVersion', currentVersion);
		}

		if(parseFloat(ProxyAddonBar.prefs.getCharPref('extensions.firex.installedVersion')) < currentVersion) {
			ProxyAddonBar.prefs.setCharPref('extensions.firex.installedVersion', currentVersion.toString());

			return true;
		}

		return firstRun;
	}
};

window.addEventListener("load", function(e) {
	var popup = document.getElementById('proxy-popup');
	popup.addEventListener('mouseenter', function(e) {
		if(!e.relatedTarget) {
			this.addEventListener('popuphiding', ProxyAddonBar.preventHide, false);
		}
	});
	popup.addEventListener('mouseleave', function(e) {
		if(!e.relatedTarget) {
			this.removeEventListener('popuphiding', ProxyAddonBar.preventHide, false);
		}
	});

	ProxyAddonBar.onLoad(document.getElementById('firex-string-bundle'));

	document.getElementById('ip-address').children[0].value = ProxyAddonBar.getIPAddress() || ProxyAddonBar.stringBundle.getString('proxyIsDisabled');
}, false);<|endoftext|>


<commit_before><commit_msg>chore(docs): use done() in gen-docs.js<commit_after><|endoftext|>


<commit_before>var fillActionBook = function(data) {
    view.fillFields(data, 'name,phone,email,term,pawn', 'val');
    $('#date').val((data.date === null) ?
        view.normalDateFormat(new Date()) :
        view.normalDateFormat(new Date(data.date)));
};

doAjaxQuery('GET', '/admin/api/v1/books/' + pathNameUrl[3], null, function(res) {
    view.fillBookInfo(res.data);
    if (res.data.event !== null) {
        fillActionBook(res.data);
    }
    settingStatusForButton(res.data.event);
});

var pathNameUrl = $(location).attr('pathname').split('/');

var settingStatusForButton = function(val) {
    var name, data_busy, disabled;
    if (val === null) {
        name = 'Выдать книгу';
        data_busy = false;
        disabled = true;
    } else {
        name = 'Принять книгу';
        data_busy = true;
        disabled = false;
    }
    $('.btnBookAction').text(name).attr('data', data_busy);
    $('#renewalOfBook').attr('disabled', disabled);
};

/* ----------------------- Pressing the action button ---------------------- */
var updateTermBook = function(data, update) {

    doAjaxQuery('POST', '/admin/api/v1/books/' + data.id + '/renewal', update, function(res) {
        $('#renewalOfBook').prop('checked', false);
        $('#name,#phone,#email,#pawn').attr('disabled', false);
    });
    msg = "Человек стремится к знаниям!\nНу разве это не прекрасно?";
    view.showSuccess(msg);
};

var takeBook = function(data, update) {
    doAjaxQuery('GET', '/admin/api/v1/books/' + data.id + '/take', update, function(res) {
        $('.orderBlock input').val('');
    });
    msg = "Общий уровень знаний на планете ощутимо повысился! ";
    view.showSuccess(msg);
};

/* ----------------------- Pressing the action button ---------------------- */
$('.btnBookAction').click(function(event) {
    var status = $('.btnBookAction').attr('data');
    var data = {
        id: $('#id').attr('book-id')
    };
    if (status == 'true') {
        var obj, update, msg, flag, isChecked = $('#renewalOfBook').prop('checked');
        update = {
            changes: view.selectFields('term,pawn', 'val')
        };
        if (isChecked) {
            updateTermBook(data, update);
            settingStatusForButton(true);
        } else {
            takeBook(data, update);
            settingStatusForButton(null);
        }
    } else {
        data.reader = view.selectFields('name,email,phone', 'val');
        doAjaxQuery('POST', '/admin/api/v1/readers/add', data, function(res) {
            data.event = view.selectFields('term,pawn', 'val');
            data.event.reader_id = res.data.reader_id;
            data.event.date = new Date();
            doAjaxQuery('POST', '/admin/api/v1/books/' + data.id + '/give', data, function(res) {
                settingStatusForButton(true);
            });
        });
        view.showSuccess('Не забудьте про залог! ))');
    }
});

/* ----------------------- Pressing button edit book ----------------------- */
$('#btnEditBook').click(function(event) {
    window.location.href = '/admin/book/update/' + pathNameUrl[3] + '';
});
/* --------------------- Pressing button remove book ----------------------- */
$('#btnRemoveBook').click(function(event) {
    var data = {
        id: $('#bookID').attr('book-id')
    };
    view.showConfirm(data.id);
});

/* ---------------------- Click checked renewal book ----------------------- */
$('#renewalOfBook').click(function(event) {
    var isChecked = $('#renewalOfBook').prop('checked');
    if (isChecked) {
        $('.btnBookAction').text('Update').attr('data-update', true);
        $('#name, #phone, #email, #pawn').attr('disabled', true);
    } else {
        $('#name,#phone,#email,#pawn').attr('disabled', false);
        var isBusy = $('.btnBookAction').attr('data');
        var val = (isBusy !== 'true') ? null : isBusy;
        settingStatusForButton(val);
    }
});
<commit_msg>added comments in admin_book.js<commit_after>/* -------------------- Filling out the book data ------------------------- */
var fillActionBook = function(data) {
    view.fillFields(data, 'name,phone,email,term,pawn', 'val');
    $('#date').val((data.date === null) ?
        view.normalDateFormat(new Date()) :
        view.normalDateFormat(new Date(data.date)));
};

/* ------------------ Obtaining data book with id -------------------------- */
doAjaxQuery('GET', '/admin/api/v1/books/' + pathNameUrl[3], null, function(res) {
    view.fillBookInfo(res.data);
    if (res.data.event !== null) {
        fillActionBook(res.data);
    }
    settingStatusForButton(res.data.event);
});

var pathNameUrl = $(location).attr('pathname').split('/');

/* ------------------- Changing the status of a button --------------------- */
var settingStatusForButton = function(val) {
    var name, data_busy, disabled;
    if (val === null) {
        name = 'Выдать книгу';
        data_busy = false;
        disabled = true;
    } else {
        name = 'Принять книгу';
        data_busy = true;
        disabled = false;
    }
    $('.btnBookAction').text(name).attr('data', data_busy);
    $('#renewalOfBook').attr('disabled', disabled);
};

/* ----------------------- Update the field term --------------------------- */
var updateTermBook = function(data, update) {

    doAjaxQuery('POST', '/admin/api/v1/books/' + data.id + '/renewal', update, function(res) {
        $('#renewalOfBook').prop('checked', false);
        $('#name,#phone,#email,#pawn').attr('disabled', false);
    });
    msg = "Человек стремится к знаниям!\nНу разве это не прекрасно?";
    view.showSuccess(msg);
};

// ------------------- They gave a book in his hands, and recorded the event,  // ---------------------- also recorded in the data reader data base.
var takeBook = function(data, update) {
    doAjaxQuery('GET', '/admin/api/v1/books/' + data.id + '/take', update, function(res) {
        $('.orderBlock input').val('');
    });
    msg = "Общий уровень знаний на планете ощутимо повысился! ";
    view.showSuccess(msg);
};

/* ----------------------- Pressing the action button ---------------------- */
$('.btnBookAction').click(function(event) {
    var status = $('.btnBookAction').attr('data');
    var data = {
        id: $('#id').attr('book-id')
    };
    if (status == 'true') {
        var obj, update, msg, flag, isChecked = $('#renewalOfBook').prop('checked');
        update = {
            changes: view.selectFields('term,pawn', 'val')
        };
        if (isChecked) { // update term book
            updateTermBook(data, update);
            settingStatusForButton(true);
        } else { // take book user
            takeBook(data, update);
            settingStatusForButton(null);
        }
    } else {
        data.reader = view.selectFields('name,email,phone', 'val');
        doAjaxQuery('POST', '/admin/api/v1/readers/add', data, function(res) {
            data.event = view.selectFields('term,pawn', 'val');
            data.event.reader_id = res.data.reader_id;
            data.event.date = new Date();
            doAjaxQuery('POST', '/admin/api/v1/books/' + data.id + '/give', data, function(res) {
                settingStatusForButton(true);
            });
        });
        view.showSuccess('Не забудьте про залог! ))');
    }
});

/* ----------------------- Pressing button edit book ----------------------- */
$('#btnEditBook').click(function(event) {
    window.location.href = '/admin/book/update/' + pathNameUrl[3] + '';
});

/* --------------------- Pressing button remove book ----------------------- */
$('#btnRemoveBook').click(function(event) {
    var data = {
        id: $('#bookID').attr('book-id')
    };
    view.showConfirm(data.id);
});

/* ---------------------- Click checked renewal book ----------------------- */
$('#renewalOfBook').click(function(event) {
    var isChecked = $('#renewalOfBook').prop('checked');
    if (isChecked) {
        $('.btnBookAction').text('Update').attr('data-update', true);
        $('#name, #phone, #email, #pawn').attr('disabled', true);
    } else {
        $('#name,#phone,#email,#pawn').attr('disabled', false);
        var isBusy = $('.btnBookAction').attr('data');
        var val = (isBusy !== 'true') ? null : isBusy;
        settingStatusForButton(val);
    }
});
<|endoftext|>


<commit_before>define(['jquery', 'webmaker-auth-client'], function ($, WebmakerAuthClient) {
  'use strict';

  var auth = new WebmakerAuthClient({
    csrfToken: $('meta[name="csrf-token"]').attr('content')
  });

  var loginEl = $('.webmaker-login');
  var logoutEl = $('.webmaker-logout');

  function toggleUserData(userData) {
    var placeHolder = $('#identity');
    var userElement = $('div.user-name');
    var emailSpans = $('.webmaker-email-placeholder');
    var profileLink = $('.profile-link a');

    var adminBadge = ' admin';

    if (userData) {
      emailSpans.html(userData.email);
      placeHolder.html('' +
        '' + userData.username + (userData.isAdmin ? adminBadge : '') + "");
      profileLink.attr('href', '/user/#!/' + userData.username)
    } else {
      emailSpans.html('');
      userElement.html('');
    }
  }

  function onLogin(user) {
    $('#webmaker-nav').addClass('loggedin');
    toggleUserData(user);
    loginEl.hide();
    logoutEl.show();
  }

  function onLogout() {
    $('#webmaker-nav').removeClass('loggedin');
    toggleUserData();
    loginEl.show();
    logoutEl.hide();
  }

  auth.on('login', onLogin);
  auth.on('logout', onLogout);

  auth.on('error', function (err) {
    window.console.log(err);
  });

  loginEl.click(auth.login);
  logoutEl.click(auth.logout);

  return auth;
});
<commit_msg>thank goodness for ASI<commit_after>define(['jquery', 'webmaker-auth-client'], function ($, WebmakerAuthClient) {
  'use strict';

  var auth = new WebmakerAuthClient({
    csrfToken: $('meta[name="csrf-token"]').attr('content')
  });

  var loginEl = $('.webmaker-login');
  var logoutEl = $('.webmaker-logout');

  function toggleUserData(userData) {
    var placeHolder = $('#identity');
    var userElement = $('div.user-name');
    var emailSpans = $('.webmaker-email-placeholder');
    var profileLink = $('.profile-link a');

    var adminBadge = ' admin';

    if (userData) {
      emailSpans.html(userData.email);
      placeHolder.html('' +
        '' + userData.username + (userData.isAdmin ? adminBadge : '') + "");
      profileLink.attr('href', '/user/#!/' + userData.username);
    } else {
      emailSpans.html('');
      userElement.html('');
    }
  }

  function onLogin(user) {
    $('#webmaker-nav').addClass('loggedin');
    toggleUserData(user);
    loginEl.hide();
    logoutEl.show();
  }

  function onLogout() {
    $('#webmaker-nav').removeClass('loggedin');
    toggleUserData();
    loginEl.show();
    logoutEl.hide();
  }

  auth.on('login', onLogin);
  auth.on('logout', onLogout);

  auth.on('error', function (err) {
    window.console.log(err);
  });

  loginEl.click(auth.login);
  logoutEl.click(auth.logout);

  return auth;
});
<|endoftext|>


<commit_before>ClientInfo = function() {
	this.well;
	this.clientNum;
};

ClientInfo.prototype.getWell = function() {
	return this.well;
};

<<<<<<< HEAD
ClientInfo.prototype.getClientNum = function(){
	return this.clientNum;
}

ClientInfo.prototype.setWellX = function(x) {
	this.well.setX = x;
};

ClientInfo.prototype.setWellY = function(y){
	this.well.setY = y;
};

ClientInfo.prototype.setClientNum = function(num){
	this.clientNum = num;
}
=======
ClientInfo.prototype.setWell = function(well) {
	this.well = well;
};
>>>>>>> 767a885b7044b65dac647cd6e15090c2eef501c7
<commit_msg>Removed Merge Error<commit_after>ClientInfo = function() {
	this.well;
	this.clientNum;
};

ClientInfo.prototype.getWell = function() {
	return this.well;
};

ClientInfo.prototype.getClientNum = function(){
	return this.clientNum;
}

ClientInfo.prototype.setWellX = function(x) {
	this.well.setX = x;
};

ClientInfo.prototype.setWellY = function(y){
	this.well.setY = y;
};

ClientInfo.prototype.setClientNum = function(num){
	this.clientNum = num;
}
ClientInfo.prototype.setWell = function(well) {
	this.well = well;
};

<|endoftext|>


<commit_before>/* global angular, FB, BASE_URL */
angular.module('i-like-solar').factory('fb',
  function ($rootScope) {
    'use strict';
    FB.init({
      appId: '582937771761901',
      channelUrl: BASE_URL + '/channel.html',
      status: true
    });

    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = '//connect.facebook.net/en_US/all.js#xfbml=1&appId=582937771761901';
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    function getLoginStatus(cb) {
      FB.getLoginStatus(function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function login(cb, perms) {
      var obj = '';
      if (perms) obj = { scope: perms };

      FB.login(function (res) {
        cb(res);
        $rootScope.$apply();
      }, obj);
    }

    function getUser(cb) {
      FB.api('/me', function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function ui(publish, cb) {
      var appId = '582937771761901';
      publish.appId = appId;
      FB.ui(publish, cb);
    }

    return {
      getLoginStatus: getLoginStatus,
      login:          login,
      getUser:        getUser,
      ui:             ui
    };
  }
);

<commit_msg>more minor updates<commit_after>/* global angular, FB, BASE_URL */
angular.module('i-like-solar').factory('fb',
  function ($rootScope) {
    'use strict';

    var appId = '582937771761901';

    FB.init({
      appId: appId,
      channelUrl: BASE_URL + '/channel.html',
      status: true
    });

    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = '//connect.facebook.net/en_US/all.js#xfbml=1&appId=' + appId;
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    function getLoginStatus(cb) {
      FB.getLoginStatus(function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function login(cb, perms) {
      var obj = '';
      if (perms) obj = { scope: perms };

      FB.login(function (res) {
        cb(res);
        $rootScope.$apply();
      }, obj);
    }

    function getUser(cb) {
      FB.api('/me', function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    function ui(publish, cb) {
      publish.appId = appId;
      FB.ui(publish, function (res) {
        cb(res);
        $rootScope.$apply();
      });
    }

    return {
      getLoginStatus: getLoginStatus,
      login:          login,
      getUser:        getUser,
      ui:             ui
    };
  }
);

<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import {
  View,
  StyleSheet,
  Platform,
  TouchableHighlight,
  ActivityIndicator,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import Text from '../text/Text';
import fonts from '../config/fonts';

const log = () => {
  console.log('please attach method to this component'); // eslint-disable-line no-console
};

const colors = {
  facebook: '#3b5998',
  twitter: '#00aced',
  ['google-plus-official']: '#dd4b39',
  pinterest: '#cb2027',
  linkedin: '#007bb6',
  youtube: '#bb0000',
  vimeo: '#aad450',
  tumblr: '#32506d',
  instagram: '#517fa4',
  quora: '#a82400',
  foursquare: '#0072b1',
  wordpress: '#21759b',
  stumbleupon: '#EB4823',
  github: '#000000',
  ['github-alt']: '#000000',
  twitch: '#6441A5',
  medium: '#02b875',
  soundcloud: '#f50',
  gitlab: '#e14329',
  angellist: '#1c4082',
  codepen: '#000000',
};

const SocialIcon = props => {
  const {
    component,
    type,
    button,
    disabled,
    loading,
    activityIndicatorStyle,
    small,
    onPress,
    iconStyle,
    style,
    iconColor,
    title,
    raised,
    light,
    fontFamily,
    fontStyle,
    iconSize,
    onLongPress,
    fontWeight,
    ...attributes
  } = props;

  const Component = onPress || onLongPress
    ? component || TouchableHighlight
    : View;
  let loadingElement;
  if (loading) {
    loadingElement = (
      <ActivityIndicator
        animating={true}
        style={[styles.activityIndicatorStyle, activityIndicatorStyle]}
        color={iconColor || 'white'}
        size={(small && 'small') || 'large'}
      />
    );
  }
  return (
    <Component
      underlayColor={light ? 'white' : colors[type]}
      onLongPress={!disabled && (onLongPress || log)}
      onPress={(!disabled || log) && (onPress || log)}
      disabled={disabled || false}
      style={[
        raised && styles.raised,
        styles.container,
        button && styles.button,
        !button && raised && styles.icon,
        !button &&
        !light &&
        !raised && {
          width: iconSize * 2 + 4,
          height: iconSize * 2 + 4,
          borderRadius: iconSize * 2,
        },
        { backgroundColor: colors[type] },
        light && { backgroundColor: 'white' },
        style && style,
      ]}
      {...attributes}
    >
      <View style={styles.wrapper}>
        <Icon
          style={[iconStyle && iconStyle]}
          color={light ? colors[type] : iconColor}
          name={type}
          size={iconSize}
        />
        {button &&
          title &&
          <Text
            style={[
              styles.title,
              light && { color: colors[type] },
              fontFamily && { fontFamily },
              fontWeight && { fontWeight },
              fontStyle && fontStyle,
            ]}
          >
            {title}
          </Text>}
        {loading && loadingElement}
      </View>
    </Component>
  );
};

SocialIcon.propTypes = {
  component: PropTypes.element,
  type: PropTypes.string,
  button: PropTypes.bool,
  onPress: PropTypes.func,
  onLongPress: PropTypes.func,
  iconStyle: View.propTypes.style,
  style: View.propTypes.style,
  iconColor: PropTypes.string,
  title: PropTypes.string,
  raised: PropTypes.bool,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  activityIndicatorStyle: View.propTypes.style,
  small: PropTypes.string,
  iconSize: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  light: PropTypes.bool,
  fontWeight: PropTypes.string,
  fontStyle: View.propTypes.style,
  fontFamily: PropTypes.string,
};

SocialIcon.defaultProps = {
  raised: true,
  iconColor: 'white',
  iconSize: 24,
  button: false,
};

const styles = StyleSheet.create({
  container: {
    margin: 7,
    borderRadius: 30,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    paddingTop: 14,
    paddingBottom: 14,
  },
  raised: {
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .4)',
        shadowOffset: { height: 1, width: 1 },
        shadowOpacity: 1,
        shadowRadius: 1,
      },
      android: {
        elevation: 2,
      },
    }),
  },
  wrapper: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    color: 'white',
    marginLeft: 15,
    ...Platform.select({
      ios: {
        fontWeight: 'bold',
      },
      android: {
        ...fonts.android.black,
      },
    }),
  },
  icon: {
    height: 52,
    width: 52,
  },
  activityIndicatorStyle: {
    marginHorizontal: 10,
    height: 0,
  },
});

export default SocialIcon;
<commit_msg>fix(socialIcon): fontStyle prototype to Text<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import {
  View,
  StyleSheet,
  Platform,
  TouchableHighlight,
  ActivityIndicator,
  Text as NativeText,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import Text from '../text/Text';
import fonts from '../config/fonts';

const log = () => {
  console.log('please attach method to this component'); // eslint-disable-line no-console
};

const colors = {
  facebook: '#3b5998',
  twitter: '#00aced',
  ['google-plus-official']: '#dd4b39',
  pinterest: '#cb2027',
  linkedin: '#007bb6',
  youtube: '#bb0000',
  vimeo: '#aad450',
  tumblr: '#32506d',
  instagram: '#517fa4',
  quora: '#a82400',
  foursquare: '#0072b1',
  wordpress: '#21759b',
  stumbleupon: '#EB4823',
  github: '#000000',
  ['github-alt']: '#000000',
  twitch: '#6441A5',
  medium: '#02b875',
  soundcloud: '#f50',
  gitlab: '#e14329',
  angellist: '#1c4082',
  codepen: '#000000',
};

const SocialIcon = props => {
  const {
    component,
    type,
    button,
    disabled,
    loading,
    activityIndicatorStyle,
    small,
    onPress,
    iconStyle,
    style,
    iconColor,
    title,
    raised,
    light,
    fontFamily,
    fontStyle,
    iconSize,
    onLongPress,
    fontWeight,
    ...attributes
  } = props;

  const Component = onPress || onLongPress
    ? component || TouchableHighlight
    : View;
  let loadingElement;
  if (loading) {
    loadingElement = (
      <ActivityIndicator
        animating={true}
        style={[styles.activityIndicatorStyle, activityIndicatorStyle]}
        color={iconColor || 'white'}
        size={(small && 'small') || 'large'}
      />
    );
  }
  return (
    <Component
      underlayColor={light ? 'white' : colors[type]}
      onLongPress={!disabled && (onLongPress || log)}
      onPress={(!disabled || log) && (onPress || log)}
      disabled={disabled || false}
      style={[
        raised && styles.raised,
        styles.container,
        button && styles.button,
        !button && raised && styles.icon,
        !button &&
        !light &&
        !raised && {
          width: iconSize * 2 + 4,
          height: iconSize * 2 + 4,
          borderRadius: iconSize * 2,
        },
        { backgroundColor: colors[type] },
        light && { backgroundColor: 'white' },
        style && style,
      ]}
      {...attributes}
    >
      <View style={styles.wrapper}>
        <Icon
          style={[iconStyle && iconStyle]}
          color={light ? colors[type] : iconColor}
          name={type}
          size={iconSize}
        />
        {button &&
          title &&
          <Text
            style={[
              styles.title,
              light && { color: colors[type] },
              fontFamily && { fontFamily },
              fontWeight && { fontWeight },
              fontStyle && fontStyle,
            ]}
          >
            {title}
          </Text>}
        {loading && loadingElement}
      </View>
    </Component>
  );
};

SocialIcon.propTypes = {
  component: PropTypes.element,
  type: PropTypes.string,
  button: PropTypes.bool,
  onPress: PropTypes.func,
  onLongPress: PropTypes.func,
  iconStyle: View.propTypes.style,
  style: View.propTypes.style,
  iconColor: PropTypes.string,
  title: PropTypes.string,
  raised: PropTypes.bool,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  activityIndicatorStyle: View.propTypes.style,
  small: PropTypes.string,
  iconSize: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  light: PropTypes.bool,
  fontWeight: PropTypes.string,
  fontStyle: NativeText.propTypes.style,
  fontFamily: PropTypes.string,
};

SocialIcon.defaultProps = {
  raised: true,
  iconColor: 'white',
  iconSize: 24,
  button: false,
};

const styles = StyleSheet.create({
  container: {
    margin: 7,
    borderRadius: 30,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  button: {
    paddingTop: 14,
    paddingBottom: 14,
  },
  raised: {
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .4)',
        shadowOffset: { height: 1, width: 1 },
        shadowOpacity: 1,
        shadowRadius: 1,
      },
      android: {
        elevation: 2,
      },
    }),
  },
  wrapper: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    color: 'white',
    marginLeft: 15,
    ...Platform.select({
      ios: {
        fontWeight: 'bold',
      },
      android: {
        ...fonts.android.black,
      },
    }),
  },
  icon: {
    height: 52,
    width: 52,
  },
  activityIndicatorStyle: {
    marginHorizontal: 10,
    height: 0,
  },
});

export default SocialIcon;
<|endoftext|>


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

var testThereAreFourTypesOfCoins = function() {
  var coins = getCoins();
  assert.equal(coins.length, 4);
};

var test = function() {
  testThereAreFourTypesOfCoins();
};

test();
<commit_msg>define coins<commit_after>var assert = require('assert');

var getCoins = function() {
  return [1,5,10,25];
};

var testThereAreFourTypesOfCoins = function() {
  var coins = getCoins();
  assert.equal(coins.length, 4);
};

var test = function() {
  testThereAreFourTypesOfCoins();
};

test();
<|endoftext|>


<commit_before>var VideoInfo = {
    init: function() {
        EventSystem.addEventListener('video_started_playing_successfully', function(video) {
            switch (video.type) {
                case 'youtube':
                    VideoInfo.loadYouTubeVideoInfo(video);
                    break;
                case 'soundcloud':
                    VideoInfo.loadSoundCloudTrackInfo(video);
                    break;
                case 'officialfm':
                    VideoInfo.loadOfficialFmTrackInfo(video);
                    break;
            }
        });
        EventSystem.addEventListener('video_info_fetched', VideoInfo.loadLinko);
        EventSystem.addEventListener('video_info_fetched', function(videoInfo) {
            switch (videoInfo.video.type) {
                case 'youtube':
                    VideoInfo.loadYouTubeUploader(videoInfo);
                    break;
                case 'soundcloud':
                    break;
                case 'officialfm':
                    break;
            }
        });
    },

    loadYouTubeUploader: function(videoInfo) {
		var url = videoInfo.author.uri + "?callback=?";
		var params = {
			'alt': 'json-in-script',
			'prettyprint': true,
			'v': 2
		};

        var info = videoInfo.author;

		$.getJSON(url, params, function(data) {
            info.url = 'http://www.youtube.com/user/' + encodeURIComponent(data.entry.yt$username.$t);
            info.avatar_url = data.entry.media$thumbnail.url;
            EventSystem.callEventListeners('uploader_info_fetched', info);
        });
    },

	loadOfficialFmTrackInfo: function(video) {
        var url = "http://api.official.fm/track/" + video.videoId;
        var params = {
            format: 'json',
            key: OFFICIALFM_API_KEY
        };
        var info = {
            video: video
        };
        $.getJSON(url, params, function(data) {
            data = data[0];
            info.video.title = data.title;
            info.video.duration = data.length * 1000;
            info.title = data.title;
            info.description = data.description;
            info.thumbnail = data.picture_absolute_url;
            info.author = {
                name: data.artist_string,
                url: data.web_url || data.buy_url,
                user_id: data.user_id
            };
            EventSystem.callEventListeners('video_info_fetched', info);
            EventSystem.callEventListeners('uploader_info_fetched', info.author);
        });
    },

	loadSoundCloudTrackInfo: function(video) {
        var url = "http://api.soundcloud.com/tracks/" + video.videoId + ".json";
        var params = {
            client_id: SOUNDCLOUD_API_KEY
        };
        var info = {
            video: video
        };
        $.getJSON(url, params, function(data) {
            info.url = data.permalink_url;
            info.title = data.title;
            info.thumbnail = data.artwork_url;
            info.description = data.description;
            info.author = {
                name: data.user.username,
                avatar_url: data.user.avatar_url,
                url: data.user.permalink_url,
                uri: data.user.uri
            };
            EventSystem.callEventListeners('video_info_fetched', info);
            EventSystem.callEventListeners('uploader_info_fetched', info.author);
        });
    },

	loadYouTubeVideoInfo: function(video) {
		var url = "http://gdata.youtube.com/feeds/api/videos/" + video.videoId + "?callback=?";
		var params = {
			'alt': 'json-in-script',
			'prettyprint': true,
			'v': 2
		};

        var info = {
            video: video
        };

		$.getJSON(url, params, function(data) {
			info.author = {
                name: data.entry.author[0].name.$t,
                uri: data.entry.author[0].uri.$t
            };
			info.title = data.entry.title.$t;

            try {
                info.description = data.entry.media$group.media$description.$t;
            } catch (e1) {
                info.description = '';
            }

            try {
                info.thumbnail = data.entry.media$group.media$thumbnail[0].url;
            } catch (e2) {
                info.thumbnail = null;
            }

            EventSystem.callEventListeners('video_info_fetched', info);
		});
	},

    loadLinko: function(info) {
        var artist = Utils.extractArtist(info.title);

        if (artist) {
            var url = 'http://linko.fruktsallad.net/artist/' + (artist.replace(/ /g, '_')) + '.json?callback=?';
            $.getJSON(url, {}, function(data) {
                if (!data || !data.links || !data.hasOwnProperty('artist_name')) {
                    return;
                } else {
                    if (data.links.hasOwnProperty('Twitter')) {
                        EventSystem.callEventListeners('artist_twitter_account_found', data.links.Twitter);
                    }
                }
            });
        }
    }
};
<commit_msg>Fix URLs to OfficialFM tracks<commit_after>var VideoInfo = {
    init: function() {
        EventSystem.addEventListener('video_started_playing_successfully', function(video) {
            switch (video.type) {
                case 'youtube':
                    VideoInfo.loadYouTubeVideoInfo(video);
                    break;
                case 'soundcloud':
                    VideoInfo.loadSoundCloudTrackInfo(video);
                    break;
                case 'officialfm':
                    VideoInfo.loadOfficialFmTrackInfo(video);
                    break;
            }
        });
        EventSystem.addEventListener('video_info_fetched', VideoInfo.loadLinko);
        EventSystem.addEventListener('video_info_fetched', function(videoInfo) {
            switch (videoInfo.video.type) {
                case 'youtube':
                    VideoInfo.loadYouTubeUploader(videoInfo);
                    break;
                case 'soundcloud':
                    break;
                case 'officialfm':
                    break;
            }
        });
    },

    loadYouTubeUploader: function(videoInfo) {
		var url = videoInfo.author.uri + "?callback=?";
		var params = {
			'alt': 'json-in-script',
			'prettyprint': true,
			'v': 2
		};

        var info = videoInfo.author;

		$.getJSON(url, params, function(data) {
            info.url = 'http://www.youtube.com/user/' + encodeURIComponent(data.entry.yt$username.$t);
            info.avatar_url = data.entry.media$thumbnail.url;
            EventSystem.callEventListeners('uploader_info_fetched', info);
        });
    },

	loadOfficialFmTrackInfo: function(video) {
        var url = "http://api.official.fm/track/" + video.videoId;
        var params = {
            format: 'json',
            key: OFFICIALFM_API_KEY
        };
        var info = {
            video: video
        };
        $.getJSON(url, params, function(data) {
            data = data[0];
            info.video.title = data.title;
            info.video.duration = data.length * 1000;
            info.url = 'http://official.fm/tracks/' + data.id;
            info.title = data.title;
            info.description = data.description;
            info.thumbnail = data.picture_absolute_url;
            info.author = {
                name: data.artist_string,
                url: data.web_url || data.buy_url,
                user_id: data.user_id
            };
            EventSystem.callEventListeners('video_info_fetched', info);
            EventSystem.callEventListeners('uploader_info_fetched', info.author);
        });
    },

	loadSoundCloudTrackInfo: function(video) {
        var url = "http://api.soundcloud.com/tracks/" + video.videoId + ".json";
        var params = {
            client_id: SOUNDCLOUD_API_KEY
        };
        var info = {
            video: video
        };
        $.getJSON(url, params, function(data) {
            info.url = data.permalink_url;
            info.title = data.title;
            info.thumbnail = data.artwork_url;
            info.description = data.description;
            info.author = {
                name: data.user.username,
                avatar_url: data.user.avatar_url,
                url: data.user.permalink_url,
                uri: data.user.uri
            };
            EventSystem.callEventListeners('video_info_fetched', info);
            EventSystem.callEventListeners('uploader_info_fetched', info.author);
        });
    },

	loadYouTubeVideoInfo: function(video) {
		var url = "http://gdata.youtube.com/feeds/api/videos/" + video.videoId + "?callback=?";
		var params = {
			'alt': 'json-in-script',
			'prettyprint': true,
			'v': 2
		};

        var info = {
            video: video
        };

		$.getJSON(url, params, function(data) {
			info.author = {
                name: data.entry.author[0].name.$t,
                uri: data.entry.author[0].uri.$t
            };
			info.title = data.entry.title.$t;

            try {
                info.description = data.entry.media$group.media$description.$t;
            } catch (e1) {
                info.description = '';
            }

            try {
                info.thumbnail = data.entry.media$group.media$thumbnail[0].url;
            } catch (e2) {
                info.thumbnail = null;
            }

            EventSystem.callEventListeners('video_info_fetched', info);
		});
	},

    loadLinko: function(info) {
        var artist = Utils.extractArtist(info.title);

        if (artist) {
            var url = 'http://linko.fruktsallad.net/artist/' + (artist.replace(/ /g, '_')) + '.json?callback=?';
            $.getJSON(url, {}, function(data) {
                if (!data || !data.links || !data.hasOwnProperty('artist_name')) {
                    return;
                } else {
                    if (data.links.hasOwnProperty('Twitter')) {
                        EventSystem.callEventListeners('artist_twitter_account_found', data.links.Twitter);
                    }
                }
            });
        }
    }
};
<|endoftext|>