<commit_before>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Router for opening query when session is initialized
 */
var QueryRouter = Backbone.Router.extend({
    routes: {
        'query/open/*query_name': 'open_query',
        'query/open': 'open_query_repository'
    },

    open_query: function(query_name) {
        Settings.ACTION = "OPEN_QUERY";
        var options = {};
        var dataType = "text";
        if (!Settings.BIPLUGIN5 && Settings.BIPLUGIN) {
            var file = (Settings.GET.SOLUTION ? (Settings.GET.SOLUTION + "/") : "") +
                       (Settings.GET.PATH && Settings.GET.PATH != "/" ? (Settings.GET.PATH + "/") : "") +
                       (Settings.GET.ACTION || "");
            options = {
                file: file
            };
        } else {
            options = {
                file: query_name
            };
        }

        var params = _.extend({
                file: options.file
            }, Settings.PARAMS);

        var dialog = {
            populate: function(repository) {
                if (repository && repository.length > 0) {
                    var f = repository[0];
                    var query = new Query(params,{ name: options.file });
                    Saiku.tabs.add(new Workspace({ query: query, item: repository[0] }));

                } else {
                    Saiku.tabs.add(new Workspace());
                }
                Settings.INITIAL_QUERY = false;
            }
        };

		var repositoryFile = new Repository({}, { dialog: dialog, file: options.file }).fetch({ async: false, data: { path: options.file }});

    },

    open_query_repository: function( ) {
        Toolbar.prototype.open_query( );
    }
});

Saiku.routers.push(new QueryRouter());
<commit_msg>fix repository so it actually returns stuff on specified paths<commit_after>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

/**
 * Router for opening query when session is initialized
 */
var QueryRouter = Backbone.Router.extend({
    routes: {
        'query/open/*query_name': 'open_query',
        'query/open': 'open_query_repository'
    },

    open_query: function(query_name) {
        Settings.ACTION = "OPEN_QUERY";
        var options = {};
        var dataType = "text";
        if (!Settings.BIPLUGIN5 && Settings.BIPLUGIN) {
            var file = (Settings.GET.SOLUTION ? (Settings.GET.SOLUTION + "/") : "") +
                       (Settings.GET.PATH && Settings.GET.PATH != "/" ? (Settings.GET.PATH + "/") : "") +
                       (Settings.GET.ACTION || "");
            options = {
                file: file
            };
        } else {
            options = {
                file: query_name
            };
        }

        var params = _.extend({
                file: options.file
            }, Settings.PARAMS);

        var dialog = {
            populate: function(repository) {
                if (repository && repository.length > 0) {
                    var f = repository[0];
                    var query = new Query(params,{ name: options.file });

                    Saiku.tabs.add(new Workspace({ query: query, item: repository[0] }));

                } else {
                    Saiku.tabs.add(new Workspace());
                }
                Settings.INITIAL_QUERY = false;
            }
        };

		var repositoryFile = new Repository({}, { dialog: dialog, file: options.file }).fetch({ async: false, data: { path: options.file }});

    },

    open_query_repository: function( ) {
        Toolbar.prototype.open_query( );
    }
});

Saiku.routers.push(new QueryRouter());
<|endoftext|>


<commit_before>var app = angular.module('VinculacionApp');

app.service('proyectos', function($http) {
   var direccion = 'http://proyecto-vinculacion.getsandbox.com/proyectos';//http://vinculacionbackend.apphb.com/

   this.getProyectos = function(numCuenta, callback) {
       //Mas adelante se utilizara el numero de cuenta para obtener los proyectos de un alumno/docente en especifico.
      //$http.get(direccion + '/' + numCuenta).then(callback);
       $http.get(direccion).then(callback);
   }
})<commit_msg>Cambio de la direccion de los proyectos<commit_after>var app = angular.module('VinculacionApp');

app.service('proyectos', function($http) {
   var direccion = 'http://vinculacionbackend.apphb.com/api/Proyects';

   this.getProyectos = function(numCuenta, callback) {
       //Mas adelante se utilizara el numero de cuenta para obtener los proyectos de un alumno/docente en especifico.
      //$http.get(direccion + '/' + numCuenta).then(callback);
       $http.get(direccion + "/1").then(callback);
   }
})<|endoftext|>


<commit_before>frappe.listview_settings['Asset'] = {
	add_fields: ['image']
}<commit_msg>fix: asset status not shwoing in the list view<commit_after>frappe.listview_settings['Asset'] = {
	add_fields: ['status'],
	get_indicator: function (doc) {
		if (doc.status === "Fully Depreciated") {
			return [__("Fully Depreciated"), "green", "status,=,Fully Depreciated"];

		} else if (doc.status === "Partially Depreciated") {
			return [__("Partially Depreciated"), "grey", "status,=,Partially Depreciated"];

		} else if (doc.status === "Sold") {
			return [__("Sold"), "green", "status,=,Sold"];

		} else if (doc.status === "Scrapped") {
			return [__("Scrapped"), "grey", "status,=,Scrapped"];

		} else if (doc.status === "In Maintenance") {
			return [__("In Maintenance"), "orange", "status,=,In Maintenance"];

		} else if (doc.status === "Out of Order") {
			return [__("Out of Order"), "grey", "status,=,Out of Order"];

		} else if (doc.status === "Issue") {
			return [__("Issue"), "orange", "status,=,Issue"];

		} else if (doc.status === "Receipt") {
			return [__("Receipt"), "green", "status,=,Receipt"];

		} else if (doc.status === "Submitted") {
			return [__("Submitted"), "blue", "status,=,Submitted"];

		} else if (doc.status === "Draft") {
			return [__("Draft"), "red", "status,=,Draft"];

		}

	},
}<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var ExportFilesWebpackPlugin = require('export-files-webpack-plugin');

var pkg = require('./package.json');

var isProduction = process.env.NODE_ENV === 'production';

module.exports = {
  mode: process.env.NODE_ENV || 'development',
  devtool: 'eval-source-map',
  entry: isProduction
    ? ['./demo/src/js/index']
    : [
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/only-dev-server',
        './demo/src/js/index'
      ],
  output: {
    path: path.join(__dirname, 'demo/dist'),
    filename: 'js/bundle.js'
  },
  plugins: [
    new CleanWebpackPlugin(isProduction ? ['demo/dist'] : []),
    new HtmlWebpackPlugin({
      inject: true,
      template: 'demo/src/index.html',
      filename: 'index.html',
      package: pkg
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    })
  ].concat(
    isProduction
      ? [
          new webpack.optimize.UglifyJsPlugin({
            compress: { warnings: false },
            output: { comments: false }
          })
        ]
      : [
          new ExportFilesWebpackPlugin('demo/dist/index.html'),
          new webpack.HotModuleReplacementPlugin()
        ]
  ),
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [
          path.join(__dirname, 'src'),
          path.join(__dirname, 'demo/src/js')
        ]
      }
    ]
  },
  devServer: isProduction
    ? null
    : {
        quiet: false,
        port: 3000,
        hot: true,
        stats: {
          chunkModules: false,
          colors: true
        },
        historyApiFallback: true
      }
};
<commit_msg>chore(redux-devtools-inspector): fix webpack config<commit_after>var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var ExportFilesWebpackPlugin = require('export-files-webpack-plugin');

var pkg = require('./package.json');

var isProduction = process.env.NODE_ENV === 'production';

module.exports = {
  mode: process.env.NODE_ENV || 'development',
  devtool: 'eval-source-map',
  entry: isProduction
    ? ['./demo/src/js/index']
    : [
        'webpack-dev-server/client?http://localhost:3000',
        'webpack/hot/only-dev-server',
        './demo/src/js/index'
      ],
  output: {
    path: path.join(__dirname, 'demo/dist'),
    filename: 'js/bundle.js'
  },
  plugins: [
    new CleanWebpackPlugin(isProduction ? ['demo/dist'] : []),
    new HtmlWebpackPlugin({
      inject: true,
      template: 'demo/src/index.html',
      filename: 'index.html',
      package: pkg
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    })
  ].concat(
    isProduction
      ? []
      : [
          new ExportFilesWebpackPlugin('demo/dist/index.html'),
          new webpack.HotModuleReplacementPlugin()
        ]
  ),
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        include: [
          path.join(__dirname, 'src'),
          path.join(__dirname, 'demo/src/js')
        ]
      }
    ]
  },
  devServer: isProduction
    ? null
    : {
        quiet: false,
        port: 3000,
        hot: true,
        stats: {
          chunkModules: false,
          colors: true
        },
        historyApiFallback: true
      }
};
<|endoftext|>


<commit_before>import actions from '../actions';

class SurveyScope {
  constructor ({survey}) {
    this.survey = survey;
  }
  add_row_to_question_library (row) {
    if (row.constructor.kls === 'Row') {
      actions.resources.createAsset({
        content: JSON.stringify({
          survey: [
            row.toJSON2()
          ]
        })
      });
    } else {
      console.error('cannot add group to question library');
    }
  }
  handleItem({position, itemData}) {
    actions.survey.addItemAtPosition({position: position, uid: itemData.uid, survey: this.survey});
  }
}

export default SurveyScope;
<commit_msg>fixes method to create library items<commit_after>import actions from '../actions';
import {
  notify,
  t,
} from '../utils';

class SurveyScope {
  constructor ({survey}) {
    this.survey = survey;
  }
  add_row_to_question_library (row) {
    if (row.constructor.kls === 'Row') {
      actions.resources.createResource({
        asset_type: 'question',
        content: JSON.stringify({
          survey: [
            row.toJSON2()
          ]
        })
      }).then(function(){
        notify(t('question has been added to the library'));
      });
    } else {
      console.error('cannot add group to question library');
    }
  }
  handleItem({position, itemData}) {
    actions.survey.addItemAtPosition({position: position, uid: itemData.uid, survey: this.survey});
  }
}

export default SurveyScope;
<|endoftext|>


<commit_before>
var sequence = {};

//it is necessary to determine which pole of the DNA...
//sequence is to the left and which is to the right...
//the default is 5'-DNAHERE-3'.
//if not oriented properly..
// primers won't function for PCR
/*" By convention, if the base sequence of a single strand of DNA is given,
 the left end of the sequence is 5' end, while the right end of the
  sequence is the 3' end."
AND
"All known DNA replication systems require a free 3' hydroxyl group
 before synthesis can be initiated"
*/

//returns substring from beginning of seq (in 5'-to-3' format)
//Forward primer is oriented the same as original sequence.
sequence.genPrimer = function(primerStart, primerLength, forward) {
	if (forward){
		return sequence.actual.substring(primerStart, primerStart+primerLength);
	}
	else {
		return sequence.genComplement(sequence.actual.substring(sequence.actual.length-primerStart, sequence.actual.length - (primerStart+primerLength)));
	}
//gets substring from end of seq then returns complement in (3'-to-5' format)
//Reverse primer must be oriented 5'-to-3' prior to chemical evaluation
};

//function to generate a pseudo random DNA sequence (non-degenerate bases)
sequence.genRandomSeq = function(seqLength) {
	var dnaBases = ["A", "T", "G", "C"];
	var ampSeqPlus = "";
	for (i = 0; i < seqLength; i++) {
		ampSeqPlus = ampSeqPlus + dnaBases[Math.floor(Math.random() * dnaBases.length) ];
	}
	return ampSeqPlus;
};

//returns the compliment of the param 'sequence' as sequence is presented. i.e.
//	sequence = "ATTTTAGCGATCCC"
//	returns  = "TAAAATCGCTAGGG"
// f_seq is for "forward sequence"
sequence.genComplement = function(f_seq) {
	var compliment = "";
	var decoder = {
		"T": "A",
		"A": "T",
		"C": "G",
		"G": "C"
	};
	for (i = 0; i < f_seq.length; i++) {
		compliment += decoder[f_seq[i]];
	}
	return compliment;
};

//function that validates sequence integrity
	//only A,G,T, and C bases => true
	//bases other than A,G,T, or C => false
sequence.seqIntegrityCheck = function (sequence) {
	var checker = 0;
	checker = sequence.search(/[~ATGC]/);
	if (checker === 0) {return true;}
	else {return false;}
};

// finds GC content of sequence
//should return a number between 0 and 1.
// e.g. given "GGCC" => 1.0
      //given "GATC" => 0.5
      //given "CCCC" => 1.0
      //given "AATC" => 0.25
sequence.calcGCContent = function(seq) {
  return (sequence.actual.split("G").length + sequence.actual.split("C").length - 2) / sequence.actual.length;
    };

seqLength = 64;
// later, this will be user input via form field or accession number.
sequence.actual = sequence.genRandomSeq(seqLength);
sequence.forwardPrimer = sequence.genPrimer(0, 18, true);
sequence.reversePrimer = sequence.genPrimer(0, 21, false);
sequence.gcContent = sequence.calcGCContent();
<commit_msg>Added a melting temp func; needs work<commit_after>
var sequence = {};

//it is necessary to determine which pole of the DNA...
//sequence is to the left and which is to the right...
//the default is 5'-DNAHERE-3'.
//if not oriented properly..
// primers won't function for PCR
/*" By convention, if the base sequence of a single strand of DNA is given,
 the left end of the sequence is 5' end, while the right end of the
  sequence is the 3' end."
AND
"All known DNA replication systems require a free 3' hydroxyl group
 before synthesis can be initiated"
*/

//returns substring from beginning of seq (in 5'-to-3' format)
//Forward primer is oriented the same as original sequence.
sequence.genPrimer = function(primerStart, primerLength, forward) {
	if (forward){
		return sequence.actual.substring(primerStart, primerStart+primerLength);
	}
	else {
		return sequence.genComplement(sequence.actual.substring(sequence.actual.length-primerStart, sequence.actual.length - (primerStart+primerLength)));
	}
//gets substring from end of seq then returns complement in (3'-to-5' format)
//Reverse primer must be oriented 5'-to-3' prior to chemical evaluation
};

//function to generate a pseudo random DNA sequence (non-degenerate bases)
sequence.genRandomSeq = function(seqLength) {
	var dnaBases = ["A", "T", "G", "C"];
	var ampSeqPlus = "";
	for (i = 0; i < seqLength; i++) {
		ampSeqPlus = ampSeqPlus + dnaBases[Math.floor(Math.random() * dnaBases.length) ];
	}
	return ampSeqPlus;
};

//returns the compliment of the param 'sequence' as sequence is presented. i.e.
//	sequence = "ATTTTAGCGATCCC"
//	returns  = "TAAAATCGCTAGGG"
// f_seq is for "forward sequence"
sequence.genComplement = function(f_seq) {
	var compliment = "";
	var decoder = {
		"T": "A",
		"A": "T",
		"C": "G",
		"G": "C"
	};
	for (i = 0; i < f_seq.length; i++) {
		compliment += decoder[f_seq[i]];
	}
	return compliment;
};

//function that validates sequence integrity
	//only A,G,T, and C bases => true
	//bases other than A,G,T, or C => false
sequence.seqIntegrityCheck = function (sequence) {
	var checker = 0;
	checker = sequence.search(/[~ATGC]/);
	if (checker === 0) {return true;}
	else {return false;}
};

// finds GC content of sequence
//should return a number between 0 and 1.
// e.g. given "GGCC" => 1.0
      //given "GATC" => 0.5
      //given "CCCC" => 1.0
      //given "AATC" => 0.25
sequence.calcGCContent = function() {
  return (sequence.actual.split("G").length + sequence.actual.split("C").length - 2) / sequence.actual.length;
    };

sequence.calcMeltingTemp = function()

seqLength = 64;
// later, this will be user input via form field or accession number.
sequence.actual = sequence.genRandomSeq(seqLength);
sequence.forwardPrimer = sequence.genPrimer(0, 18, true);
sequence.reversePrimer = sequence.genPrimer(0, 21, false);
sequence.gcContent = sequence.calcGCContent();

<|endoftext|>


<commit_before>(function () {
  /*global env*/
  var dfm = require('./dfm');
  var config = null;
  var items = [];
  var itemsMap = {};
  var base = '_yamlGeneratorOutput';
  var globalUid = 'global';
  var uidPrefix = '';
  var yamlMime = '### YamlMime:UniversalReference';
  var outputFileExt = '.yml';
  var jsdocConfigPath = '_jsdocConfTemp.json';
  var builtInTypes = ['array','arraybuffer','asyncfunction','atomics','boolean','dataview','date','error','evalerror','float32array','float64array','function','generator','generatorfunction','infinity','int16array','int32array','int8array','internalerror','intl','intl.collator','intl.datetimeformat','intl.numberformat','iterator','json','map','math','nan','number','object','parallelarray','promise','proxy','rangeerror','referenceerror','reflect','regexp','simd','simd.bool16x8','simd.bool32x4','simd.bool64x2','simd.bool8x16','simd.float32x4','simd.float64x2','simd.int16x8','simd.int32x4','simd.int8x16','simd.uint16x8','simd.uint32x4','simd.uint8x16','set','sharedarraybuffer','stopiteration','string','symbol','syntaxerror','typeerror','typedarray','urierror','uint16array','uint32array','uint8array','uint8clampedarray','weakmap','weakset', 'undefined'];

  function addItem(item) {
    if (itemsMap[item.uid] && item.summary === '') {
      return;
    }
    item.langs = ['js'];
    // javascript dosen't allow method / class with the same name
    if (itemsMap[item.uid] !== undefined && items[items.length - 1].uid == item.uid) {
      items[items.length - 1] = item;
    } else {
      if (item.type === 'Class') {
        // put class in front of item array to ensure serialize won't skip anything useful.
        items.unshift(item);
      } else {
        items.push(item);
      }
    }
    itemsMap[item.uid] = item;
  }

  function setSourceInfo(item, doclet) {
    if (config.repo) {
      var path = doclet.meta.path.replace(env.pwd + '\\', '') + '\\' + doclet.meta.filename;
      if (path.split('\\').length > 2) {
        path = path.split('\\').splice(2).join('\\');
      }
      item.source = {
        id: item.id,
        path: path,
        startLine: doclet.meta.lineno,
        remote: {
          branch: config.repo.branch,
          path: path,
          repo: config.repo.url
        }
      };
    }
  }

  function handleClass(item, doclet) {
    item.type = 'Class';
    item.summary = dfm.convertLinkToGfm(doclet.classdesc, uidPrefix);
    var ctor = {
      id: item.id + '.#ctor',
      uid: item.uid + '.#ctor',
      parent: item.uid,
      name: item.name,
      fullName: item.fullName + '.' + item.name,
      summary: dfm.convertLinkToGfm(doclet.description, uidPrefix)
    };
    handleFunction(ctor, doclet);
    item.children = [ctor.uid];
    addItem(ctor);
  }

  function handleFunction(item, doclet) {
    item.type = doclet.kind === 'function' ? 'Function' : 'Constructor';
    item.syntax = {};
    // set parameters
    if (doclet.params !== undefined) {
      item.syntax.parameters = doclet.params.map(function (p) {
        return {
          id: p.name,
          type: handleParameterType(p.type),
          description: dfm.convertLinkToGfm(p.description, uidPrefix),
          optional: p.optional
        };
      });
    }
    // set name and fullName
    var params = [];
    (item.syntax.parameters || []).forEach(function (p) {
      if (p.id.indexOf('.') < 0) params.push(p.id);
    });
    item.name += '(' + params.join(', ') + ')';
    item.fullName += '(' + params.join(', ') + ')';
    // set return type
    if (doclet.returns != undefined) {
      item.syntax.return = {
        type: handleParameterType(doclet.returns[0].type),
        description: dfm.convertLinkToGfm(doclet.returns[0].description, uidPrefix),
        optional: doclet.returns[0].optional
      };
    }
    // set syntax
    // which one is better:
    // 1. function method_name(arg1, arg2, ...);
    // 2. return_type function method_name(arg1, arg2)
    // 3. function method_name(arg1, arg2) -> return_type
    item.syntax.content = (item.type === 'Function' ? 'function ' : 'new ') + item.name;

    function handleParameterType(type) {
      if (!type) return undefined;
      return type.names.map(function (n) {
        if (builtInTypes.indexOf(n.toLowerCase()) == -1) {
          n = uidPrefix + n;
        }
        return n;
      });
    }
  }

  function handleMember(item, doclet) {
    item.type = 'Member';
    // set type
    item.syntax = {};
    if (doclet.type != undefined) {
      item.syntax.return = {
        type: [doclet.type.names[0]]
      };
    }
    // set syntax
    item.syntax.content = item.name;
  }

  function serialize() {
    var serializer = require('js-yaml');
    var fs = require('fs');
    var classes = {};
    var fileMap = {};
    if (!fs.existsSync(base)) {
      fs.mkdirSync(base);
    }
    items.forEach(function (item) {
      switch (item.type) {
      case 'Class':
        classes[item.uid] = {
          items: [item],
          referenceMap: {}
        };
        fileMap[item.uid] = item.uid;
        break;
      case 'Constructor':
      case 'Function':
      case 'Member':
        var parentId = item.parent || globalUid;
        var parent = classes[parentId];
        if (parent === undefined) {
          console.log(parentId + ' is not a class, ignored.');
          break;
        }
        parent.items.push(item);
        if (parentId === globalUid) {
          (parent.items[0].children = parent.items[0].children || []).push(item.uid);
        }
        fileMap[item.uid] = parentId;
        (item.syntax.parameters || []).forEach(function (p) {
          (p.type || []).forEach(function (t) {
            classes[parentId].referenceMap[t] = true;
          });
        });
        if (item.syntax.return) {
          (item.syntax.return.type || []).forEach(function (t) {
            classes[parentId].referenceMap[t] = true;
          });
        }
        break;
      }
    });

    var toc = [];
    for (var id in classes) {
      var classItem = classes[id];
      // build references
      classItem.references = [];
      for (var r in classItem.referenceMap) {
        var f = fileMap[r];
        if (f !== undefined && f !== id) {
          classItem.references.push({
            uid: r,
            name: r.indexOf('.') == -1 ? r : r.substring(r.indexOf('.') + 1),
            fullName: r,
            isExternal: f === undefined
          });
        }
      }
      classItem.referenceMap = undefined;
      if (classItem.references.length == 0) {
        classItem.references = undefined;
      }

      // something wrong in js-yaml, workaround it by serialize and deserialize from JSON
      classItem = JSON.parse(JSON.stringify(classItem));
      // replace \r, \n, space with dash
      // filter global without children
      if (id == globalUid && (!classItem.items[0].children || classItem.items[0].children.length === 0)) {
        continue;
      }

      var fileName = id.replace(/[ \n\r]/g, '-') + outputFileExt;
      if (fileName && fileName.split('.').length > 2) {
        fileName = fileName.split('.').splice(1).join('.');
      }
      fs.writeFileSync(base + '/' + fileName, yamlMime + '\n' + serializer.safeDump(classItem));
      console.log(fileName + ' generated.');

      var tocItem = {
        uid: id,
        name: classItem.items[0].name
      };
      // add methods but constructor method to toc
      if (classItem.items.length > 1) {
        for (var itemIndex in classItem.items) {
          var item = classItem.items[itemIndex];
          if (item.type === 'Function') {
            (tocItem.items = tocItem.items || []).push({
              uid: item.id,
              name: item.name.replace(/\(.*\)/, '')
            });
          }
        }
      }
      toc.push(tocItem);
    }
    toc.sort(function (a, b) {
      // sort classes alphabetically, but GLOBAL at last
      if (a.uid === globalUid) {
        return 1;
      }
      if (b.uid === globalUid) {
        return -1;
      }
      var nameA = a.name.toUpperCase();
      var nameB = b.name.toUpperCase();
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }

      return 0;
    });

    fs.writeFileSync(base + '/toc.yml', serializer.safeDump(toc));
    console.log('toc.yml generated.');
  }

  var typeMap = {
    'member': handleMember,
    'function': handleFunction,
    'class': handleClass
  };

  exports.handlers = {
    newDoclet: function (e) {
      var doclet = e.doclet;
      // ignore anything whose parent is not a doclet
      // except it's a class made with help function
      if (doclet.memberof !== undefined && itemsMap[uidPrefix + doclet.memberof] === undefined && doclet.kind !== 'class') {
        return;
      }
      // ignore unrecognized kind
      if (typeMap[doclet.kind] === undefined) {
        console.log('unrecognized kind: ' + doclet.kind);
        return;
      }
      // ignore unexported global member
      if (doclet.memberof === undefined && doclet.kind != 'class' && !(doclet.meta && doclet.meta.code && doclet.meta.code.name && doclet.meta.code.name.indexOf('exports') == 0)) {
        return;
      }
      // ignore inner function or member
      if (doclet.kind === 'member' && doclet.scope === 'inner') {
        return;
      }

      // ignore doclet without doucment
      if (doclet.undocumented === true) {
        return;
      }

      // ignore empty longname
      if (!doclet.longname) {
        return;
      }
      var parent = '';
      if (doclet.memberof === undefined && doclet.kind !== 'class') {
        parent = '_global.';
      }
      // basic properties
      var item = {
        uid: uidPrefix + parent + doclet.longname,
        id: uidPrefix + parent + doclet.longname,
        parent: (doclet.memberof && doclet.kind !== 'class') ? (uidPrefix + doclet.memberof) : undefined,
        name: doclet.name,
        summary: doclet.description ? dfm.convertLinkToGfm(doclet.description, uidPrefix) : dfm.convertLinkToGfm(doclet.summary, uidPrefix)
      };
      // set parent
      if (item.parent !== undefined) {
        parent = itemsMap[item.parent];
        (parent.children = parent.children || []).push(item.uid);
      }
      // set full name
      item.fullName = (item.parent ? item.parent + '.' : uidPrefix) + item.name;

      // set source info
      if (doclet.kind === 'class') {
        setSourceInfo(item, doclet);
      }

      // pass custom tags
      if ('tags' in doclet) {
        item.tags = doclet.tags;
      }

      typeMap[doclet.kind](item, doclet);
      addItem(item);
    },
    parseBegin: function () {
      var fse = require('fs-extra');
      var path = require('path');
      config = fse.readJsonSync(jsdocConfigPath);

      // copy readme.md to index.md
      if (config.readme) {
        fse.copySync(config.readme, path.join(base, 'index.md'));
      }

      // parse package.json to use package name
      if (config.package) {
        var packageJson = fse.readJsonSync(config.package);
        if (packageJson && packageJson.name) {
          globalUid = packageJson.name + '.' + globalUid;
          uidPrefix = packageJson.name + '.';
        }
      }
      items.push(
        {
          uid: globalUid,
          id: globalUid,
          name: 'GLOBAL',
          fullName: 'GLOBAL',
          type: 'Class',
          langs: ['js']
        }
      );
    },
    parseComplete: function () {
      serialize();
      // no need to generate html, directly exit process
      process.exit(0);
    }
  };
})();
<commit_msg>update plugin<commit_after>(function () {
  /*global env*/
  var dfm = require('./dfm');
  var config = null;
  var items = [];
  var itemsMap = {};
  var base = '_yamlGeneratorOutput';
  var globalUid = 'global';
  var uidPrefix = '';
  var yamlMime = '### YamlMime:UniversalReference';
  var outputFileExt = '.yml';
  var jsdocConfigPath = '_jsdocConfTemp.json';
  var builtInTypes = ['array','arraybuffer','asyncfunction','atomics','boolean','dataview','date','error','evalerror','float32array','float64array','function','generator','generatorfunction','infinity','int16array','int32array','int8array','internalerror','intl','intl.collator','intl.datetimeformat','intl.numberformat','iterator','json','map','math','nan','number','object','parallelarray','promise','proxy','rangeerror','referenceerror','reflect','regexp','simd','simd.bool16x8','simd.bool32x4','simd.bool64x2','simd.bool8x16','simd.float32x4','simd.float64x2','simd.int16x8','simd.int32x4','simd.int8x16','simd.uint16x8','simd.uint32x4','simd.uint8x16','set','sharedarraybuffer','stopiteration','string','symbol','syntaxerror','typeerror','typedarray','urierror','uint16array','uint32array','uint8array','uint8clampedarray','weakmap','weakset', 'undefined'];

  function addItem(item) {
    if (itemsMap[item.uid] && item.summary === '') {
      return;
    }
    item.langs = ['js'];
    // javascript dosen't allow method / class with the same name
    if (itemsMap[item.uid] !== undefined && items[items.length - 1].uid == item.uid) {
      items[items.length - 1] = item;
    } else {
      if (item.type === 'Class') {
        // put class in front of item array to ensure serialize won't skip anything useful.
        items.unshift(item);
      } else {
        items.push(item);
      }
    }
    itemsMap[item.uid] = item;
  }

  function setSourceInfo(item, doclet) {
    if (config.repo) {
      var path = doclet.meta.path.replace(env.pwd + '\\', '') + '\\' + doclet.meta.filename;
      if (path.split('\\').length > 2) {
        path = path.split('\\').splice(2).join('\\');
      }
      item.source = {
        id: item.id,
        path: path,
        startLine: doclet.meta.lineno,
        remote: {
          branch: config.repo.branch,
          path: path,
          repo: config.repo.url
        }
      };
    }
  }

  function handleClass(item, doclet) {
    item.type = 'Class';
    item.summary = dfm.convertLinkToGfm(doclet.classdesc, uidPrefix);
    var ctor = {
      id: item.id + '.#ctor',
      uid: item.uid + '.#ctor',
      parent: item.uid,
      name: item.name,
      fullName: item.fullName + '.' + item.name,
      summary: dfm.convertLinkToGfm(doclet.description, uidPrefix)
    };
    handleFunction(ctor, doclet);
    item.children = [ctor.uid];
    addItem(ctor);
  }

  function handleFunction(item, doclet) {
    item.type = doclet.kind === 'function' ? 'Function' : 'Constructor';
    item.syntax = {};
    // set parameters
    if (doclet.params !== undefined) {
      item.syntax.parameters = doclet.params.map(function (p) {
        return {
          id: p.name,
          type: handleParameterType(p.type),
          description: dfm.convertLinkToGfm(p.description, uidPrefix),
          optional: p.optional
        };
      });
    }
    // set name and fullName
    var params = [];
    (item.syntax.parameters || []).forEach(function (p) {
      if (p.id.indexOf('.') < 0) params.push(p.id);
    });
    item.name += '(' + params.join(', ') + ')';
    item.fullName += '(' + params.join(', ') + ')';
    // set return type
    if (doclet.returns != undefined) {
      item.syntax.return = {
        type: handleParameterType(doclet.returns[0].type),
        description: dfm.convertLinkToGfm(doclet.returns[0].description, uidPrefix),
        optional: doclet.returns[0].optional
      };
    }
    // set syntax
    // which one is better:
    // 1. function method_name(arg1, arg2, ...);
    // 2. return_type function method_name(arg1, arg2)
    // 3. function method_name(arg1, arg2) -> return_type
    item.syntax.content = (item.type === 'Function' ? 'function ' : 'new ') + item.name;

    function handleParameterType(type) {
      if (!type) return undefined;
      return type.names.map(function (n) {
        if (builtInTypes.indexOf(n.toLowerCase()) == -1) {
          n = uidPrefix + n;
        }
        return n;
      });
    }
  }

  function handleMember(item, doclet) {
    item.type = 'Member';
    // set type
    item.syntax = {};
    if (doclet.type != undefined) {
      item.syntax.return = {
        type: [doclet.type.names[0]]
      };
    }
    // set syntax
    item.syntax.content = item.name;
  }

  function serialize() {
    var serializer = require('js-yaml');
    var fs = require('fs');
    var classes = {};
    var fileMap = {};
    if (!fs.existsSync(base)) {
      fs.mkdirSync(base);
    }
    items.forEach(function (item) {
      switch (item.type) {
      case 'Class':
        classes[item.uid] = {
          items: [item],
          referenceMap: {}
        };
        fileMap[item.uid] = item.uid;
        break;
      case 'Constructor':
      case 'Function':
      case 'Member':
        var parentId = item.parent || globalUid;
        var parent = classes[parentId];
        if (parent === undefined) {
          console.log(parentId + ' is not a class, ignored.');
          break;
        }
        parent.items.push(item);
        if (parentId === globalUid) {
          (parent.items[0].children = parent.items[0].children || []).push(item.uid);
        }
        fileMap[item.uid] = parentId;
        (item.syntax.parameters || []).forEach(function (p) {
          (p.type || []).forEach(function (t) {
            classes[parentId].referenceMap[t] = true;
          });
        });
        if (item.syntax.return) {
          (item.syntax.return.type || []).forEach(function (t) {
            classes[parentId].referenceMap[t] = true;
          });
        }
        break;
      }
    });

    var toc = [];
    for (var id in classes) {
      var classItem = classes[id];
      // build references
      classItem.references = [];
      for (var r in classItem.referenceMap) {
        var f = fileMap[r];
        if (f !== undefined && f !== id) {
          classItem.references.push({
            uid: r,
            name: r.indexOf('.') == -1 ? r : r.substring(r.indexOf('.') + 1),
            fullName: r,
            isExternal: f === undefined
          });
        }
      }
      classItem.referenceMap = undefined;
      if (classItem.references.length == 0) {
        classItem.references = undefined;
      }

      // something wrong in js-yaml, workaround it by serialize and deserialize from JSON
      classItem = JSON.parse(JSON.stringify(classItem));
      // replace \r, \n, space with dash
      // filter global without children
      if (id == globalUid && (!classItem.items[0].children || classItem.items[0].children.length === 0)) {
        continue;
      }

      var fileName = id.replace(/[ \n\r]/g, '-') + outputFileExt;
      if (fileName && fileName.split('.').length > 2) {
        fileName = fileName.split('.').splice(1).join('.');
      }
      fs.writeFileSync(base + '/' + fileName, yamlMime + '\n' + serializer.safeDump(classItem));
      console.log(fileName + ' generated.');

      var tocItem = {
        uid: id,
        name: classItem.items[0].name
      };
      // add methods but constructor method to toc
      if (classItem.items.length > 1) {
        for (var itemIndex in classItem.items) {
          var item = classItem.items[itemIndex];
          if (item.type === 'Function') {
            (tocItem.items = tocItem.items || []).push({
              uid: item.id,
              name: item.name.replace(/\(.*\)/, '')
            });
          }
        }
      }
      toc.push(tocItem);
    }
    toc.sort(function (a, b) {
      // sort classes alphabetically, but GLOBAL at last
      if (a.uid === globalUid) {
        return 1;
      }
      if (b.uid === globalUid) {
        return -1;
      }
      var nameA = a.name.toUpperCase();
      var nameB = b.name.toUpperCase();
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }

      return 0;
    });

    fs.writeFileSync(base + '/toc.yml', serializer.safeDump(toc));
    console.log('toc.yml generated.');
  }

  var typeMap = {
    'member': handleMember,
    'function': handleFunction,
    'class': handleClass
  };

  exports.handlers = {
    newDoclet: function (e) {
      var doclet = e.doclet;
      // ignore anything whose parent is not a doclet
      // except it's a class made with help function
      if (doclet.memberof !== undefined && itemsMap[uidPrefix + doclet.memberof] === undefined && doclet.kind !== 'class') {
        return;
      }
      // ignore unrecognized kind
      if (typeMap[doclet.kind] === undefined) {
        console.log('unrecognized kind: ' + doclet.kind);
        return;
      }
      // ignore unexported global member
      if (doclet.memberof === undefined && doclet.kind != 'class' && !(doclet.meta && doclet.meta.code && doclet.meta.code.name && doclet.meta.code.name.indexOf('exports') == 0)) {
        return;
      }
      // ignore inner function or member
      if (doclet.kind === 'member' && doclet.scope === 'inner') {
        return;
      }

      // ignore doclet without doucment
      if (doclet.undocumented === true) {
        return;
      }

      // ignore empty longname
      if (!doclet.longname) {
        return;
      }
      var parent = '';
      if (doclet.memberof === undefined && doclet.kind !== 'class') {
        parent = '_global.';
      }
      // basic properties
      var item = {
        uid: uidPrefix + parent + doclet.longname,
        id: uidPrefix + parent + doclet.longname,
        parent: (doclet.memberof && doclet.kind !== 'class') ? (uidPrefix + doclet.memberof) : undefined,
        name: doclet.name,
        summary: doclet.description ? dfm.convertLinkToGfm(doclet.description, uidPrefix) : dfm.convertLinkToGfm(doclet.summary, uidPrefix)
      };
      // set parent
      if (item.parent !== undefined) {
        parent = itemsMap[item.parent];
        (parent.children = parent.children || []).push(item.uid);
      }
      // set full name
      item.fullName = (item.parent ? item.parent + '.' : uidPrefix) + item.name;

      // set source info
      if (doclet.kind === 'class') {
        setSourceInfo(item, doclet);
      }

      // pass custom tags
      if ('tags' in doclet) {
        item.tags = doclet.tags;
      }

      typeMap[doclet.kind](item, doclet);
      addItem(item);
    },
    parseBegin: function () {
      var fse = require('fs-extra');
      var path = require('path');
      config = fse.readJsonSync(jsdocConfigPath);

      if (config.repo && config.repo.url && !config.repo.url.endsWith('.git')) {
        config.repo.url = config.repo.url + '.git';
      }

      // copy readme.md to index.md
      if (config.readme) {
        fse.copySync(config.readme, path.join(base, 'index.md'));
      }

      // parse package.json to use package name
      if (config.package) {
        var packageJson = fse.readJsonSync(config.package);
        if (packageJson && packageJson.name) {
          globalUid = packageJson.name + '.' + globalUid;
          uidPrefix = packageJson.name + '.';
        }
      }
      items.push(
        {
          uid: globalUid,
          id: globalUid,
          name: 'GLOBAL',
          fullName: 'GLOBAL',
          type: 'Class',
          langs: ['js']
        }
      );
    },
    parseComplete: function () {
      serialize();
      // no need to generate html, directly exit process
      process.exit(0);
    }
  };
})();
<|endoftext|>


<commit_before>const assert = require("assert");
const util = require("util"); // eslint-disable-line no-unused-vars

const TruffleDecoder = require("../../../truffle-decoder");
const TruffleCodecUtils = require("../../../truffle-codec-utils");

const DecodingSample = artifacts.require("DecodingSample");

function validateStructS(struct, values) {
  assert.equal(typeof struct, "object");
  assert.equal(struct.structInt.toString(), values[0]);
  assert.equal(struct.structString, values[1]);
  assert.equal(struct.structBool, values[2]);
  assert.equal(struct.structAddress, values[3]);

  const s2 = struct.structS2;
  validateStructS2(s2, values[4]);
}

function validateStructS2(s2, values) {
  assert.equal(typeof s2, "object");
  assert.equal(s2.structTwoFixedArrayUint[0].toString(), values[0]);
  assert.equal(s2.structTwoFixedArrayUint[1].toString(), values[1]);
  assert.equal(s2.structTwoDynamicArrayUint.length, values[2]);
  for (let i = 0; i < values[2]; i++) {
    assert.equal(s2.structTwoDynamicArrayUint[i].toString(), values[3 + i]);
  }
}

contract("DecodingSample", _accounts => {
  it("should get the initial state properly", async () => {
    let deployedContract = await DecodingSample.deployed();
    let address = deployedContract.address;
    const decoder = await TruffleDecoder.forContract(
      DecodingSample,
      [],
      web3.currentProvider
    );

    decoder.watchMappingKey("varMapping", 2);
    decoder.watchMappingKey("varMapping", 3);

    const initialState = await decoder.state();

    // used for debugging test results
    // console.log(
    //   util.inspect(initialState, {
    //     showHidden: false,
    //     depth: null,
    //     colors: true
    //   })
    // );

    assert.equal(initialState.name, "DecodingSample");
    const variables = TruffleCodecUtils.Conversion.nativizeVariables(
      initialState.variables
    );

    assert.notStrictEqual(typeof variables.varUint, "undefined");

    assert.equal(variables.varUint.toString(), "1");
    assert.equal(variables.varString, "two");
    assert.equal(variables.varBool, true);
    assert.equal(
      variables.varAddress,
      "0x12345567890abcDEffEDcBa09876543211337121"
    );
    assert.equal(variables.varBytes7, "0x78554477331122");
    assert.equal(variables.varBytes, "0x01030307");
    assert.equal(typeof variables.varEnum, "string");
    assert.equal(variables.varEnum, "DecodingSample.E.EnumValTwo");

    const struct = variables.varStructS;
    validateStructS(struct, [
      "-2",
      "three",
      false,
      "0x54321567890abcdeFfEDcBA09876543211337121",
      ["4", "2", 3, "4", "8", "12"]
    ]);

    assert.equal(variables.fixedArrayUint[0].toString(), "16");
    assert.equal(variables.fixedArrayUint[1].toString(), "17");
    assert.equal(variables.fixedArrayString[0].toString(), "hello");
    assert.equal(variables.fixedArrayString[1].toString(), "world");
    assert.equal(variables.fixedArrayBool[0], true);
    assert.equal(variables.fixedArrayBool[1], false);
    assert.equal(
      variables.fixedArrayAddress[0].toString(),
      "0x98761567890ABCdeffEdCba09876543211337121"
    );
    assert.equal(
      variables.fixedArrayAddress[1].toString(),
      "0xfEDc1567890aBcDeFfEdcba09876543211337121"
    );
    assert.equal(variables.fixedArrayBytes7[0].toString(), "0x75754477331122");
    assert.equal(variables.fixedArrayBytes7[1].toString(), "0xe7d14477331122");
    assert.equal(variables.fixedArrayByte[0].toString(), "0x37");
    assert.equal(variables.fixedArrayByte[1].toString(), "0xbe");
    assert.equal(variables.fixedArrayEnum[0], "DecodingSample.E.EnumValFour");
    assert.equal(variables.fixedArrayEnum[1], "DecodingSample.E.EnumValTwo");

    assert.equal(variables.dynamicArrayUint[0].toString(), "16");
    assert.equal(variables.dynamicArrayUint[1].toString(), "17");
    assert.equal(variables.dynamicArrayString[0].toString(), "hello");
    assert.equal(variables.dynamicArrayString[1].toString(), "world");
    assert.equal(variables.dynamicArrayBool[0], true);
    assert.equal(variables.dynamicArrayBool[1], false);
    assert.equal(
      variables.dynamicArrayAddress[0].toString(),
      "0x98761567890ABCdeffEdCba09876543211337121"
    );
    assert.equal(
      variables.dynamicArrayAddress[1].toString(),
      "0xfEDc1567890aBcDeFfEdcba09876543211337121"
    );
    assert.equal(
      variables.dynamicArrayBytes7[0].toString(),
      "0x75754477331122"
    );
    assert.equal(
      variables.dynamicArrayBytes7[1].toString(),
      "0xe7d14477331122"
    );
    assert.equal(variables.dynamicArrayByte[0].toString(), "0x37");
    assert.equal(variables.dynamicArrayByte[1].toString(), "0xbe");
    assert.equal(variables.dynamicArrayEnum[0], "DecodingSample.E.EnumValFour");
    assert.equal(variables.dynamicArrayEnum[1], "DecodingSample.E.EnumValTwo");

    // const fixedStructArray = variables.fixedArrayStructS;

    assert.equal(variables.varMapping[2], 41);
    assert.equal(variables.varMapping[3], 107);

    assert.equal(
      variables.functionExternal,
      "DecodingSample(" + address + ").example"
    );
  });
});
<commit_msg>Update test<commit_after>const assert = require("assert");
const util = require("util"); // eslint-disable-line no-unused-vars

const TruffleDecoder = require("../../../truffle-decoder");
const TruffleCodecUtils = require("../../../truffle-codec-utils");

const DecodingSample = artifacts.require("DecodingSample");

function validateStructS(struct, values) {
  assert.equal(typeof struct, "object");
  assert.equal(struct.structInt.toString(), values[0]);
  assert.equal(struct.structString, values[1]);
  assert.equal(struct.structBool, values[2]);
  assert.equal(struct.structAddress, values[3]);

  const s2 = struct.structS2;
  validateStructS2(s2, values[4]);
}

function validateStructS2(s2, values) {
  assert.equal(typeof s2, "object");
  assert.equal(s2.structTwoFixedArrayUint[0].toString(), values[0]);
  assert.equal(s2.structTwoFixedArrayUint[1].toString(), values[1]);
  assert.equal(s2.structTwoDynamicArrayUint.length, values[2]);
  for (let i = 0; i < values[2]; i++) {
    assert.equal(s2.structTwoDynamicArrayUint[i].toString(), values[3 + i]);
  }
}

contract("DecodingSample", _accounts => {
  it("should get the initial state properly", async () => {
    let deployedContract = await DecodingSample.deployed();
    let address = deployedContract.address;
    const decoder = await TruffleDecoder.forContractInstance(
      DecodingSample,
      [],
      web3.currentProvider
    );

    decoder.watchMappingKey("varMapping", 2);
    decoder.watchMappingKey("varMapping", 3);

    const initialState = await decoder.state();

    // used for debugging test results
    // console.log(
    //   util.inspect(initialState, {
    //     showHidden: false,
    //     depth: null,
    //     colors: true
    //   })
    // );

    assert.equal(initialState.name, "DecodingSample");
    const variables = TruffleCodecUtils.Conversion.nativizeVariables(
      initialState.variables
    );

    assert.notStrictEqual(typeof variables.varUint, "undefined");

    assert.equal(variables.varUint.toString(), "1");
    assert.equal(variables.varString, "two");
    assert.equal(variables.varBool, true);
    assert.equal(
      variables.varAddress,
      "0x12345567890abcDEffEDcBa09876543211337121"
    );
    assert.equal(variables.varBytes7, "0x78554477331122");
    assert.equal(variables.varBytes, "0x01030307");
    assert.equal(typeof variables.varEnum, "string");
    assert.equal(variables.varEnum, "DecodingSample.E.EnumValTwo");

    const struct = variables.varStructS;
    validateStructS(struct, [
      "-2",
      "three",
      false,
      "0x54321567890abcdeFfEDcBA09876543211337121",
      ["4", "2", 3, "4", "8", "12"]
    ]);

    assert.equal(variables.fixedArrayUint[0].toString(), "16");
    assert.equal(variables.fixedArrayUint[1].toString(), "17");
    assert.equal(variables.fixedArrayString[0].toString(), "hello");
    assert.equal(variables.fixedArrayString[1].toString(), "world");
    assert.equal(variables.fixedArrayBool[0], true);
    assert.equal(variables.fixedArrayBool[1], false);
    assert.equal(
      variables.fixedArrayAddress[0].toString(),
      "0x98761567890ABCdeffEdCba09876543211337121"
    );
    assert.equal(
      variables.fixedArrayAddress[1].toString(),
      "0xfEDc1567890aBcDeFfEdcba09876543211337121"
    );
    assert.equal(variables.fixedArrayBytes7[0].toString(), "0x75754477331122");
    assert.equal(variables.fixedArrayBytes7[1].toString(), "0xe7d14477331122");
    assert.equal(variables.fixedArrayByte[0].toString(), "0x37");
    assert.equal(variables.fixedArrayByte[1].toString(), "0xbe");
    assert.equal(variables.fixedArrayEnum[0], "DecodingSample.E.EnumValFour");
    assert.equal(variables.fixedArrayEnum[1], "DecodingSample.E.EnumValTwo");

    assert.equal(variables.dynamicArrayUint[0].toString(), "16");
    assert.equal(variables.dynamicArrayUint[1].toString(), "17");
    assert.equal(variables.dynamicArrayString[0].toString(), "hello");
    assert.equal(variables.dynamicArrayString[1].toString(), "world");
    assert.equal(variables.dynamicArrayBool[0], true);
    assert.equal(variables.dynamicArrayBool[1], false);
    assert.equal(
      variables.dynamicArrayAddress[0].toString(),
      "0x98761567890ABCdeffEdCba09876543211337121"
    );
    assert.equal(
      variables.dynamicArrayAddress[1].toString(),
      "0xfEDc1567890aBcDeFfEdcba09876543211337121"
    );
    assert.equal(
      variables.dynamicArrayBytes7[0].toString(),
      "0x75754477331122"
    );
    assert.equal(
      variables.dynamicArrayBytes7[1].toString(),
      "0xe7d14477331122"
    );
    assert.equal(variables.dynamicArrayByte[0].toString(), "0x37");
    assert.equal(variables.dynamicArrayByte[1].toString(), "0xbe");
    assert.equal(variables.dynamicArrayEnum[0], "DecodingSample.E.EnumValFour");
    assert.equal(variables.dynamicArrayEnum[1], "DecodingSample.E.EnumValTwo");

    // const fixedStructArray = variables.fixedArrayStructS;

    assert.equal(variables.varMapping[2], 41);
    assert.equal(variables.varMapping[3], 107);

    assert.equal(
      variables.functionExternal,
      "DecodingSample(" + address + ").example"
    );
  });
});
<|endoftext|>


<commit_before>/*******************************************************************************
 * Code contributed to the webinos project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Copyright 2011 Alexander Futasz, Fraunhofer FOKUS
 ******************************************************************************/

(function () {
    function isOnNode() {
        return typeof module === "object" ? true : false;
    }

    // TODO The typeMap is hard-coded here so only these APIs are
    // supported. In the future this should be improved to support
    // dynamic APIs.
    //
    // APIs should be classified as intrinsic ones and webinos
    // services. Intrinsic APIs, like Discovery, App2App, should be
    // provided directly in WRT. webinos service APIs, like Actuator,
    // Vehicle, which are supposed to be provided with a PZP, should be
    // found with Discovery implemented in this file.
    //
    // That means, intrinsic APIs are released along with WRT and not
    // acquired with Discovery. Users can invoke them directly just
    // like using a library. While webinos service APIs will still be
    // acquired with Discovery.
    //
    var typeMap = {};
    if (typeof ActuatorModule !== 'undefined') typeMap['http://webinos.org/api/actuators'] = ActuatorModule;
    if (typeof App2AppModule !== 'undefined') typeMap['http://webinos.org/api/app2app'] = App2AppModule;
    if (typeof AppLauncherModule !== 'undefined') typeMap['http://webinos.org/api/applauncher'] = AppLauncherModule;
    if (typeof AuthenticationModule !== 'undefined') typeMap['http://webinos.org/api/authentication'] = AuthenticationModule;
    if (typeof webinos.Context !== 'undefined') typeMap['http://webinos.org/api/context'] = webinos.Context;
    if (typeof corePZinformationModule !== 'undefined') typeMap['http://webinos.org/api/corePZinformation'] = corePZinformationModule;
    if (typeof DiscoveryModule !== 'undefined') typeMap['http://webinos.org/api/discovery'] = DiscoveryModule;
    if (typeof EventsModule !== 'undefined') typeMap['http://webinos.org/api/events'] = EventsModule;
    if (webinos.file && webinos.file.Service) typeMap['http://webinos.org/api/file'] = webinos.file.Service;
    if (typeof MediaContentModule !== 'undefined') typeMap['http://webinos.org/api/mediacontent'] = MediaContentModule;
    if (typeof NfcModule !== 'undefined') typeMap['http://webinos.org/api/nfc'] = NfcModule;
    if (typeof WebNotificationModule !== 'undefined') typeMap['http://webinos.org/api/notifications'] = WebNotificationModule;
    if (typeof WebinosDeviceOrientation !== 'undefined') typeMap['http://webinos.org/api/deviceorientation'] = WebinosDeviceOrientation;
    if (typeof PaymentModule !== 'undefined') typeMap['http://webinos.org/api/payment'] = PaymentModule;
    if (typeof Sensor !== 'undefined') typeMap['http://webinos.org/api/sensors'] = Sensor;
    if (typeof TestModule !== 'undefined') typeMap['http://webinos.org/api/test'] = TestModule;
    if (typeof TVManager !== 'undefined') typeMap['http://webinos.org/api/tv'] = TVManager;
    if (typeof Vehicle !== 'undefined') typeMap['http://webinos.org/api/vehicle'] = Vehicle;
    if (typeof WebinosGeolocation !== 'undefined') typeMap['http://webinos.org/api/w3c/geolocation'] = WebinosGeolocation;
    if (typeof WebinosGeolocation !== 'undefined') typeMap['http://www.w3.org/ns/api-perms/geolocation'] = WebinosGeolocation; // old feature URI for compatibility
    if (typeof Contacts !== 'undefined') typeMap['http://www.w3.org/ns/api-perms/contacts'] = Contacts;
    if (typeof ZoneNotificationModule !== 'undefined') typeMap['http://webinos.org/api/internal/zonenotification'] = ZoneNotificationModule;
//    if (typeof DiscoveryModule !== 'undefined') typeMap['http://webinos.org/manager/discovery/bluetooth'] = DiscoveryModule;
    if (typeof oAuthModule !== 'undefined') typeMap['http://webinos.org/mwc/oauth'] = oAuthModule;
    if (typeof DeviceStatusManager !== 'undefined') typeMap['http://webinos.org/api/devicestatus'] = DeviceStatusManager;

    if (isOnNode()) {
        var path = require('path');
        var moduleRoot = path.resolve(__dirname, '../') + '/';
        var moduleDependencies = require(moduleRoot + '/dependencies.json');
        var webinosRoot = path.resolve(moduleRoot + moduleDependencies.root.location) + '/';
        var dependencies = require(path.resolve(webinosRoot + '/dependencies.json'));

        var Context = require(path.join(webinosRoot, dependencies.wrt.location, 'lib/webinos.context.js')).Context;
        typeMap['http://webinos.org/api/context'] = Context;
    }

    /**
     * Interface DiscoveryInterface
     */
    var ServiceDiscovery = function (rpcHandler) {
        var _webinosReady = false;
        var callerCache = [];

        /**
         * Search for registered services.
         * @param {ServiceType} serviceType ServiceType object to search for.
         * @param {FindCallBack} callback Callback to call with results.
         * @param {Options} options Timeout, optional.
         * @param {Filter} filter Filters based on location, name, description, optional.
         */
        this.findServices = function (serviceType, callback, options, filter) {
            var that = this;
            var findOp;

            var rpc = rpcHandler.createRPC('ServiceDiscovery', 'findServices',
                    [serviceType, options, filter]);

            var timer = setTimeout(function () {
                rpcHandler.unregisterCallbackObject(rpc);
                // If no results return TimeoutError.
                if (!findOp.found && typeof callback.onError === 'function') {
                    callback.onError(new DOMError('TimeoutError', ''));
                }
            }, options && typeof options.timeout !== 'undefined' ?
                        options.timeout : 120000 // default timeout 120 secs
            );

            findOp = new PendingOperation(function() {
                // remove waiting requests from callerCache
                var index = callerCache.indexOf(rpc);
                if (index >= 0) {
                    callerCache.splice(index, 1);
                }
                rpcHandler.unregisterCallbackObject(rpc);
                if (typeof callback.onError === 'function') {
                    callback.onError(new DOMError('AbortError', ''));
                }
            }, timer);

            var success = function (params) {
                console.log("servicedisco: service found.");
                var baseServiceObj = params;

                // reduce feature uri to base form, e.g. http://webinos.org/api/sensors
                // instead of http://webinos.org/api/sensors.light etc.
                var stype = /(?:.*(?:\/[\w]+)+)/.exec(baseServiceObj.api);
                stype = stype ? stype[0] : undefined;

                var ServiceConstructor = typeMap[stype];
                if (ServiceConstructor) {
                    // elevate baseServiceObj to usable local WebinosService object
                    var service = new ServiceConstructor(baseServiceObj, rpcHandler);
                    findOp.found = true;
                    callback.onFound(service);
                } else {
                    var serviceErrorMsg = 'Cannot instantiate webinos service.';
                    console.log(serviceErrorMsg);
                    if (typeof callback.onError === 'function') {
                        callback.onError(new DiscoveryError(102, serviceErrorMsg));
                    }
                }
            }; // End of function success

            // The core of findService.
            rpc.onservicefound = function (params) {
                // params is the parameters needed by the API method.
                success(params);
            };

            // Refer to the call in
            // Webinos-Platform/webinos/core/api/servicedisco/lib/rpc_servicediso.js.
            rpc.onSecurityError = function (params) {
                if (typeof findOp !== 'undefined' && typeof callback.onError === 'function') {
                    callback.onError(new DOMError('SecurityError', ''));
                }
            };

            // Add this pending operation.
            rpcHandler.registerCallbackObject(rpc);

            if (typeof rpcHandler.parent !== 'undefined') {
                rpc.serviceAddress = rpcHandler.parent.config.pzhId;
            } else {
                rpc.serviceAddress = webinos.session.getServiceLocation();
            }

            if (!isOnNode() && !_webinosReady) {
                callerCache.push(rpc);
            } else {
                // Only do it when _webinosReady is true.
                rpcHandler.executeRPC(rpc);
            }

            return findOp;
        };  // End of findServices.

        if (isOnNode()) {
            return;
        }

        // further code only runs in the browser

        webinos.session.addListener('registeredBrowser', function () {
            _webinosReady = true;
            for (var i = 0; i < callerCache.length; i++) {
                var req = callerCache[i];
                rpcHandler.executeRPC(req);
            }
            callerCache = [];
        });
    };

    /**
     * Export definitions for node.js
     */
    if (isOnNode()) {
        exports.ServiceDiscovery = ServiceDiscovery;
    } else {
        // this adds ServiceDiscovery to the window object in the browser
        window.ServiceDiscovery = ServiceDiscovery;
    }

    /**
     * Interface PendingOperation
     */
    function PendingOperation(cancelFunc, timer) {
        this.found = false;

        this.cancel = function () {
            clearTimeout(timer);
            cancelFunc();
        };
    }

    function DOMError(name, message) {
        return {
            name: name,
            message: message
        };
    }

    webinos.discovery = new ServiceDiscovery (webinos.rpcHandler);
    webinos.ServiceDiscovery = webinos.discovery; // for backward compat
}());
<commit_msg>move devicestatus definition<commit_after>/*******************************************************************************
 * Code contributed to the webinos project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Copyright 2011 Alexander Futasz, Fraunhofer FOKUS
 ******************************************************************************/

(function () {
    function isOnNode() {
        return typeof module === "object" ? true : false;
    }

    // TODO The typeMap is hard-coded here so only these APIs are
    // supported. In the future this should be improved to support
    // dynamic APIs.
    //
    // APIs should be classified as intrinsic ones and webinos
    // services. Intrinsic APIs, like Discovery, App2App, should be
    // provided directly in WRT. webinos service APIs, like Actuator,
    // Vehicle, which are supposed to be provided with a PZP, should be
    // found with Discovery implemented in this file.
    //
    // That means, intrinsic APIs are released along with WRT and not
    // acquired with Discovery. Users can invoke them directly just
    // like using a library. While webinos service APIs will still be
    // acquired with Discovery.
    //
    var typeMap = {};
    if (typeof ActuatorModule !== 'undefined') typeMap['http://webinos.org/api/actuators'] = ActuatorModule;
    if (typeof App2AppModule !== 'undefined') typeMap['http://webinos.org/api/app2app'] = App2AppModule;
    if (typeof AppLauncherModule !== 'undefined') typeMap['http://webinos.org/api/applauncher'] = AppLauncherModule;
    if (typeof AuthenticationModule !== 'undefined') typeMap['http://webinos.org/api/authentication'] = AuthenticationModule;
    if (typeof webinos.Context !== 'undefined') typeMap['http://webinos.org/api/context'] = webinos.Context;
    if (typeof corePZinformationModule !== 'undefined') typeMap['http://webinos.org/api/corePZinformation'] = corePZinformationModule;
    if (typeof DeviceStatusManager !== 'undefined') typeMap['http://webinos.org/api/devicestatus'] = DeviceStatusManager;
    if (typeof DiscoveryModule !== 'undefined') typeMap['http://webinos.org/api/discovery'] = DiscoveryModule;
    if (typeof EventsModule !== 'undefined') typeMap['http://webinos.org/api/events'] = EventsModule;
    if (webinos.file && webinos.file.Service) typeMap['http://webinos.org/api/file'] = webinos.file.Service;
    if (typeof MediaContentModule !== 'undefined') typeMap['http://webinos.org/api/mediacontent'] = MediaContentModule;
    if (typeof NfcModule !== 'undefined') typeMap['http://webinos.org/api/nfc'] = NfcModule;
    if (typeof WebNotificationModule !== 'undefined') typeMap['http://webinos.org/api/notifications'] = WebNotificationModule;
    if (typeof WebinosDeviceOrientation !== 'undefined') typeMap['http://webinos.org/api/deviceorientation'] = WebinosDeviceOrientation;
    if (typeof PaymentModule !== 'undefined') typeMap['http://webinos.org/api/payment'] = PaymentModule;
    if (typeof Sensor !== 'undefined') typeMap['http://webinos.org/api/sensors'] = Sensor;
    if (typeof TestModule !== 'undefined') typeMap['http://webinos.org/api/test'] = TestModule;
    if (typeof TVManager !== 'undefined') typeMap['http://webinos.org/api/tv'] = TVManager;
    if (typeof Vehicle !== 'undefined') typeMap['http://webinos.org/api/vehicle'] = Vehicle;
    if (typeof WebinosGeolocation !== 'undefined') typeMap['http://webinos.org/api/w3c/geolocation'] = WebinosGeolocation;
    if (typeof WebinosGeolocation !== 'undefined') typeMap['http://www.w3.org/ns/api-perms/geolocation'] = WebinosGeolocation; // old feature URI for compatibility
    if (typeof Contacts !== 'undefined') typeMap['http://www.w3.org/ns/api-perms/contacts'] = Contacts;
    if (typeof ZoneNotificationModule !== 'undefined') typeMap['http://webinos.org/api/internal/zonenotification'] = ZoneNotificationModule;
//    if (typeof DiscoveryModule !== 'undefined') typeMap['http://webinos.org/manager/discovery/bluetooth'] = DiscoveryModule;
    if (typeof oAuthModule !== 'undefined') typeMap['http://webinos.org/mwc/oauth'] = oAuthModule;

    if (isOnNode()) {
        var path = require('path');
        var moduleRoot = path.resolve(__dirname, '../') + '/';
        var moduleDependencies = require(moduleRoot + '/dependencies.json');
        var webinosRoot = path.resolve(moduleRoot + moduleDependencies.root.location) + '/';
        var dependencies = require(path.resolve(webinosRoot + '/dependencies.json'));

        var Context = require(path.join(webinosRoot, dependencies.wrt.location, 'lib/webinos.context.js')).Context;
        typeMap['http://webinos.org/api/context'] = Context;
    }

    /**
     * Interface DiscoveryInterface
     */
    var ServiceDiscovery = function (rpcHandler) {
        var _webinosReady = false;
        var callerCache = [];

        /**
         * Search for registered services.
         * @param {ServiceType} serviceType ServiceType object to search for.
         * @param {FindCallBack} callback Callback to call with results.
         * @param {Options} options Timeout, optional.
         * @param {Filter} filter Filters based on location, name, description, optional.
         */
        this.findServices = function (serviceType, callback, options, filter) {
            var that = this;
            var findOp;

            var rpc = rpcHandler.createRPC('ServiceDiscovery', 'findServices',
                    [serviceType, options, filter]);

            var timer = setTimeout(function () {
                rpcHandler.unregisterCallbackObject(rpc);
                // If no results return TimeoutError.
                if (!findOp.found && typeof callback.onError === 'function') {
                    callback.onError(new DOMError('TimeoutError', ''));
                }
            }, options && typeof options.timeout !== 'undefined' ?
                        options.timeout : 120000 // default timeout 120 secs
            );

            findOp = new PendingOperation(function() {
                // remove waiting requests from callerCache
                var index = callerCache.indexOf(rpc);
                if (index >= 0) {
                    callerCache.splice(index, 1);
                }
                rpcHandler.unregisterCallbackObject(rpc);
                if (typeof callback.onError === 'function') {
                    callback.onError(new DOMError('AbortError', ''));
                }
            }, timer);

            var success = function (params) {
                console.log("servicedisco: service found.");
                var baseServiceObj = params;

                // reduce feature uri to base form, e.g. http://webinos.org/api/sensors
                // instead of http://webinos.org/api/sensors.light etc.
                var stype = /(?:.*(?:\/[\w]+)+)/.exec(baseServiceObj.api);
                stype = stype ? stype[0] : undefined;

                var ServiceConstructor = typeMap[stype];
                if (ServiceConstructor) {
                    // elevate baseServiceObj to usable local WebinosService object
                    var service = new ServiceConstructor(baseServiceObj, rpcHandler);
                    findOp.found = true;
                    callback.onFound(service);
                } else {
                    var serviceErrorMsg = 'Cannot instantiate webinos service.';
                    console.log(serviceErrorMsg);
                    if (typeof callback.onError === 'function') {
                        callback.onError(new DiscoveryError(102, serviceErrorMsg));
                    }
                }
            }; // End of function success

            // The core of findService.
            rpc.onservicefound = function (params) {
                // params is the parameters needed by the API method.
                success(params);
            };

            // Refer to the call in
            // Webinos-Platform/webinos/core/api/servicedisco/lib/rpc_servicediso.js.
            rpc.onSecurityError = function (params) {
                if (typeof findOp !== 'undefined' && typeof callback.onError === 'function') {
                    callback.onError(new DOMError('SecurityError', ''));
                }
            };

            // Add this pending operation.
            rpcHandler.registerCallbackObject(rpc);

            if (typeof rpcHandler.parent !== 'undefined') {
                rpc.serviceAddress = rpcHandler.parent.config.pzhId;
            } else {
                rpc.serviceAddress = webinos.session.getServiceLocation();
            }

            if (!isOnNode() && !_webinosReady) {
                callerCache.push(rpc);
            } else {
                // Only do it when _webinosReady is true.
                rpcHandler.executeRPC(rpc);
            }

            return findOp;
        };  // End of findServices.

        if (isOnNode()) {
            return;
        }

        // further code only runs in the browser

        webinos.session.addListener('registeredBrowser', function () {
            _webinosReady = true;
            for (var i = 0; i < callerCache.length; i++) {
                var req = callerCache[i];
                rpcHandler.executeRPC(req);
            }
            callerCache = [];
        });
    };

    /**
     * Export definitions for node.js
     */
    if (isOnNode()) {
        exports.ServiceDiscovery = ServiceDiscovery;
    } else {
        // this adds ServiceDiscovery to the window object in the browser
        window.ServiceDiscovery = ServiceDiscovery;
    }

    /**
     * Interface PendingOperation
     */
    function PendingOperation(cancelFunc, timer) {
        this.found = false;

        this.cancel = function () {
            clearTimeout(timer);
            cancelFunc();
        };
    }

    function DOMError(name, message) {
        return {
            name: name,
            message: message
        };
    }

    webinos.discovery = new ServiceDiscovery (webinos.rpcHandler);
    webinos.ServiceDiscovery = webinos.discovery; // for backward compat
}());
<|endoftext|>


<commit_before>
var UserManager = $({});
UserManager.MY_NAME_URL = B_HTTP + 'my.name';

$.extend(UserManager, {
    loginWithRetry: function(wait) {
        UserManager.login();
        var current = UserManager.user;
        setTimeout(function() {
            // retry;
            if (!UserManager.user) UserManager.login();
        }, wait || 15 * 1000);
    },
    login: function() {
        $.get(UserManager.MY_NAME_URL).next(function(data) {
            UserManager.loginHandler(JSON.parse(data));
        }).error(UserManager.loginErrorHandler);
    },
    loginHandler: function(res) {
        p('loginHandler');
        UserManager.setUser(res);
    },
    loginErrorHandler: function UserManager_loginErrorHandler(res) {
        p('login error...', res);
        var j = JSON.parse(res.responseText);
        UserManager.setUser(j);
    },
    logout: function UserManager_clearUser () {
        UserManager.clearUser();
    },
    clearUser: function() {
        if (UserManager.user) {
            UserManager.user.clear();
            delete UserManager.user;
        }
    },
    setUser: function UserManager_setCurrentUser (res) {
        if (!res.login) return;
        var current = UserManager.user;
        if (current) {
            if (current.name == res.name) {
                current.options.rks = res.rks;
                current.options.plususer = res.plususer;
                current.options.ignores_regex = res.ignores_regex;
                delete current._ignores;
                return current;
            }
            UserManager.clearUser();
        }
        var user = new User(res.name, res);
        UserManager.user = user;
        p('UserChange: ', user.name);
        UserManager.trigger('UserChange', [user]);
    }
});

var User = function(name, options) {
    this._name = name;
    this.view = new User.View(name);
    this.options = options || {};
};

User.View = function(name) {
    this.name = name;
}

User.View.prototype = {
    getProfileIcon: function(name, isLarge) {
        return sprintf('http://www.st-hatena.com/users/%s/%s/profile%s.gif',
                       name.substring(0, 2), name, isLarge ? '' : '_s');
    },
    get icon() {
        return this.getProfileIcon(this.name);
    },
    get largeIcon() {
        return this.getProfileIcon(this.name, true);
    },
};

User.prototype = {
    get name() { return this._name },
    get plususer() { return this.options.plususer == 1 },
    get rks() { return this.options.rks },
    get private() { return this.options.private == 1 },
    get public() { return !this.private },
    get canUseTwitter() { return this.options.is_oauth_twitter == 1 },
    get postTwitterChecked() { return this.options.twitter_checked || 'inherit' },
    get maxCommentLength() { return this.options.max_comment_length || 100 },
    get ignores() {
        if (this.options.ignores_regex) {
            if (typeof this._ignores == 'undefined') {
                try {
                    this._ignores = new RegExp(this.options.ignores_regex);
                } catch(e) {
                    this._ignores = null;
                }
            }
            return this._ignores;
        }
        return null;
    },
    resetDatabase: function() {
        Model.initialize(true).next(function() {
            Sync.sync();
        });
    },
    hasBookmark: function user_hasBookmark(url) {
        return Model.Bookmark.findByUrl(url).next(function(res) {
            return (res ? true : false);
        });
    },
    link: function(path) {
        return B_HTTP + this.name + '/' + (path || '');
    },
    get database() {
        return new Database('hatenabookmark-' + this.name, {
            estimatedSize: 50 * 1024 * 1024
        });
        /*
        return new Database('hatenabookmark2-' + this.name, '1.0', 'hatenabookmark-' + this.name, 1024 * 1024 * 50);
        */
    },
    get dataURL() { return sprintf(B_HTTP + '%s/search.data', this.name) },
    // get dataURL() { return sprintf(B_HTTP + 'secondlife/search.data', this.name) },
    // getProfileIcon: function user_getProfileIcon(isLarge) {
    //     return UserUtils.getProfileIcon(this.name, isLarge);
    // },

    deleteBookmark: function(url) {
        var data = {
            url: url,
            rks: this.rks,
        };
        var endpoint = this.link('api.delete_bookmark.json');
        var self = this;

        Deferred.retry(3, function() {
            return $.ajax({
                url: endpoint,
                type: 'POST',
                data: data,
                timeout: 15000,
            });
        }, {wait: 3}).next(function(res) {
            p('remote delete success - ' + url);
            Model.Bookmark.findByUrl(url).next(function(b) {
                if (b) {
                    // XXX: remove tag
                    p('delete bookmarked - ' + url);
                    HTTPCache.clearCached(url);
                    b.destroy().next(function() {
                         $(document).trigger('BookmarksUpdated');
                    });
                }
            });
        }).error(function(res) {
            Manager.deleteBookmarkError(data);
        });
    },

    saveBookmark: function(data) {
        // ["comment=%5Bhatena%5Dhatenabookmark&url=http%3A%2F%2Fb.hatena.ne.jp%2F&with_status_op=1&private=1"]
        var data = URI.parseQuery(data);
        data.rks = this.rks;
        var endpoint = this.link('add.edit.json');
        var self = this;

        p(data);
        Deferred.retry(3, function(i) {
            p('save ajax start:' + data.url + ' : ' + i);
            return $.ajax({
                url: endpoint,
                type: 'POST',
                data: data,
                timeout: 15000,
            });
        }, {wait: 3}).next(function(res) {
            p('remote save success - ' + data.url);
            if (data.confirm_bookmark) {
                setTimeout(function() {
                    Manager.confirmBookmark(URI.parse(data.url).entryURL);
                }, 10);
            }
            self.updateBookmark(data.url, res);
        }).error(function(res) {
            Manager.saveBookmarkError(data);
        });
    },
    updateBookmark: function(url, data) {
         // XXX
         try {
             data = JSON.parse(data);
         } catch(e) {
         }
         var self = this;
         Model.Bookmark.findByUrl(url).next(function(b) {
             HTTPCache.clearCached(url);
             if (b) {
                 b.set('comment', data.comment_raw || '');
                 Model.getDatabase().transaction(function() {
                     b.save().next(function() {
                         $(document).trigger('BookmarksUpdated');
                     });
                 });
             } else {
                 p('update bookmark - save sync' + Sync._syncing);
                 setTimeout(function() {
                     Sync.sync();
                     setTimeout(function() {
                         p('update bookmark - save sync retry');
                         self.hasBookmark(url).next(function(has) {
                             p('update bookmark - save sync retry if false -> ' + !!has);
                             if (!has) Sync.sync();
                         });
                     }, 10000);
                 }, 500);
             }
         });
    },
    clear: function user_clear() {
    }
};

<commit_msg>APIのURLに|?editor=craddon|を付加。<commit_after>
var UserManager = $({});
UserManager.MY_NAME_URL = B_HTTP + 'my.name';

$.extend(UserManager, {
    loginWithRetry: function(wait) {
        UserManager.login();
        var current = UserManager.user;
        setTimeout(function() {
            // retry;
            if (!UserManager.user) UserManager.login();
        }, wait || 15 * 1000);
    },
    login: function() {
        $.get(UserManager.MY_NAME_URL).next(function(data) {
            UserManager.loginHandler(JSON.parse(data));
        }).error(UserManager.loginErrorHandler);
    },
    loginHandler: function(res) {
        p('loginHandler');
        UserManager.setUser(res);
    },
    loginErrorHandler: function UserManager_loginErrorHandler(res) {
        p('login error...', res);
        var j = JSON.parse(res.responseText);
        UserManager.setUser(j);
    },
    logout: function UserManager_clearUser () {
        UserManager.clearUser();
    },
    clearUser: function() {
        if (UserManager.user) {
            UserManager.user.clear();
            delete UserManager.user;
        }
    },
    setUser: function UserManager_setCurrentUser (res) {
        if (!res.login) return;
        var current = UserManager.user;
        if (current) {
            if (current.name == res.name) {
                current.options.rks = res.rks;
                current.options.plususer = res.plususer;
                current.options.ignores_regex = res.ignores_regex;
                delete current._ignores;
                return current;
            }
            UserManager.clearUser();
        }
        var user = new User(res.name, res);
        UserManager.user = user;
        p('UserChange: ', user.name);
        UserManager.trigger('UserChange', [user]);
    }
});

var User = function(name, options) {
    this._name = name;
    this.view = new User.View(name);
    this.options = options || {};
};

User.View = function(name) {
    this.name = name;
}

User.View.prototype = {
    getProfileIcon: function(name, isLarge) {
        return sprintf('http://www.st-hatena.com/users/%s/%s/profile%s.gif',
                       name.substring(0, 2), name, isLarge ? '' : '_s');
    },
    get icon() {
        return this.getProfileIcon(this.name);
    },
    get largeIcon() {
        return this.getProfileIcon(this.name, true);
    },
};

User.prototype = {
    get name() { return this._name },
    get plususer() { return this.options.plususer == 1 },
    get rks() { return this.options.rks },
    get private() { return this.options.private == 1 },
    get public() { return !this.private },
    get canUseTwitter() { return this.options.is_oauth_twitter == 1 },
    get postTwitterChecked() { return this.options.twitter_checked || 'inherit' },
    get maxCommentLength() { return this.options.max_comment_length || 100 },
    get ignores() {
        if (this.options.ignores_regex) {
            if (typeof this._ignores == 'undefined') {
                try {
                    this._ignores = new RegExp(this.options.ignores_regex);
                } catch(e) {
                    this._ignores = null;
                }
            }
            return this._ignores;
        }
        return null;
    },
    resetDatabase: function() {
        Model.initialize(true).next(function() {
            Sync.sync();
        });
    },
    hasBookmark: function user_hasBookmark(url) {
        return Model.Bookmark.findByUrl(url).next(function(res) {
            return (res ? true : false);
        });
    },
    link: function(path) {
        return B_HTTP + this.name + '/' + (path ? path + '?editer=craddon' : '');
    },
    get database() {
        return new Database('hatenabookmark-' + this.name, {
            estimatedSize: 50 * 1024 * 1024
        });
        /*
        return new Database('hatenabookmark2-' + this.name, '1.0', 'hatenabookmark-' + this.name, 1024 * 1024 * 50);
        */
    },
    get dataURL() { return sprintf(B_HTTP + '%s/search.data', this.name) },
    // get dataURL() { return sprintf(B_HTTP + 'secondlife/search.data', this.name) },
    // getProfileIcon: function user_getProfileIcon(isLarge) {
    //     return UserUtils.getProfileIcon(this.name, isLarge);
    // },

    deleteBookmark: function(url) {
        var data = {
            url: url,
            rks: this.rks,
        };
        var endpoint = this.link('api.delete_bookmark.json');
        var self = this;

        Deferred.retry(3, function() {
            return $.ajax({
                url: endpoint,
                type: 'POST',
                data: data,
                timeout: 15000,
            });
        }, {wait: 3}).next(function(res) {
            p('remote delete success - ' + url);
            Model.Bookmark.findByUrl(url).next(function(b) {
                if (b) {
                    // XXX: remove tag
                    p('delete bookmarked - ' + url);
                    HTTPCache.clearCached(url);
                    b.destroy().next(function() {
                         $(document).trigger('BookmarksUpdated');
                    });
                }
            });
        }).error(function(res) {
            Manager.deleteBookmarkError(data);
        });
    },

    saveBookmark: function(data) {
        // ["comment=%5Bhatena%5Dhatenabookmark&url=http%3A%2F%2Fb.hatena.ne.jp%2F&with_status_op=1&private=1"]
        var data = URI.parseQuery(data);
        data.rks = this.rks;
        var endpoint = this.link('add.edit.json');
        var self = this;

        p(data);
        Deferred.retry(3, function(i) {
            p('save ajax start:' + data.url + ' : ' + i);
            return $.ajax({
                url: endpoint,
                type: 'POST',
                data: data,
                timeout: 15000,
            });
        }, {wait: 3}).next(function(res) {
            p('remote save success - ' + data.url);
            if (data.confirm_bookmark) {
                setTimeout(function() {
                    Manager.confirmBookmark(URI.parse(data.url).entryURL);
                }, 10);
            }
            self.updateBookmark(data.url, res);
        }).error(function(res) {
            Manager.saveBookmarkError(data);
        });
    },
    updateBookmark: function(url, data) {
         // XXX
         try {
             data = JSON.parse(data);
         } catch(e) {
         }
         var self = this;
         Model.Bookmark.findByUrl(url).next(function(b) {
             HTTPCache.clearCached(url);
             if (b) {
                 b.set('comment', data.comment_raw || '');
                 Model.getDatabase().transaction(function() {
                     b.save().next(function() {
                         $(document).trigger('BookmarksUpdated');
                     });
                 });
             } else {
                 p('update bookmark - save sync' + Sync._syncing);
                 setTimeout(function() {
                     Sync.sync();
                     setTimeout(function() {
                         p('update bookmark - save sync retry');
                         self.hasBookmark(url).next(function(has) {
                             p('update bookmark - save sync retry if false -> ' + !!has);
                             if (!has) Sync.sync();
                         });
                     }, 10000);
                 }, 500);
             }
         });
    },
    clear: function user_clear() {
    }
};

<|endoftext|>